我有以下XML:
<oa:Parties>
<ow-o:SupplierParty>
<oa:PartyId>
<oa:Id>1</oa:Id>
</oa:PartyId>
</ow-o:SupplierParty>
<ow-o:CustomerParty>
<oa:PartyId>
<oa:Id>123-123</oa:Id> // I NEED THIS
</oa:PartyId>
<oa:Business>
<oa:Id>ShiptoID</oa:Id>
</oa:Business>
</ow-o:CustomerParty>
</oa:Parties>如何获取123-123值?
我试过这个:
NodeList nodeList = document.getElementsByTagName("ow-o:CustomerParty");
Node parentNode = nodeList.item(0);
String ID = parentNode.getTextContent();但是它有两个<oa:Id>元素。
有没有一种方法可以根据层次结构ow-o:CustomerParty > oa:PartyId > oa:Id找到值?
发布于 2021-06-25 08:20:12
我只是在它的子项上使用了一个简单的过滤器。这边请
NodeList nodeList = document.getElementsByTagName("ow-o:CustomerParty");
Node parentNode = nodeList.item(0);
Node partyNode = filterNodeListByName(parentNode.getChildNodes(), "oa:PartyId");
Node idNode = null;
if(partyNode!=null)
idNode = filterNodeListByName(partyNode.getChildNodes(), "oa:Id")
String ID = idNode!=null ? idNode.getTextContent() : "";基本上,第一个筛选器获取与节点名称"oa:PartiId“匹配的所有子项。然后,它将找到的节点(我使用的是findAny,但在您的示例中,findFirst仍然是一个可行的选项)映射到子项节点的,名称为oa:id,文本内容
SN:我正在考虑你会这样定义一个方法
public boolean isNodeAndWithName(Node node, String expectedName) {
return node.getNodeType() == Node.ELEMENT_NODE && expectedName.equals(node.getNodeName());
}这是另一种方法
public Node filterNodeListByName(NodeList nodeList, String nodeName) {
for(int i = 0; i<nodeList.getLength(); i++)
if(isNodeAndWithName(nodeList.item(i), nodeName)
return nodeList.item(i);
return null;
}https://stackoverflow.com/questions/68123227
复制相似问题