获取Java中的特定XML标记元素



我有以下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();

但它同时具有CCD_ 2元素。

有没有一种方法可以根据层次结构ow-o:CustomerParty > oa:PartyId > oa:Id找到值?

我只想对它的子项使用一个简单的过滤器。这种方式

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;
}

最新更新