简体   繁体   English

如何使用DOM解析器按XML名称访问子节点?

[英]How to access child nodes by name in XML using DOM parser?

I have an xml file in following format: 我有以下格式的xml文件:

....
<ecs:Person>
     <ecs:abc>1234</ecs:abc>
     <ecs:def>9090</ecs:def>
</ecs:Person>
<ecs:Person>
     <ecs:def>1010</ecs:def>
</ecs:Person>
...

From above xml, we can understand that node "ecs:abc" is optional. 从上面的xml中,我们可以了解到节点“ ecs:abc”是可选的。 I want to get value of "ecs:def" for all person. 我想为所有人获得“ ecs:def”的价值。 For that I was thinking to follow below approach: 为此,我正在考虑遵循以下方法:

....
int len = d.getElementsByTagName("ecs:Person").getLength();
for(int i=0;i < personLen;i++){
    print d.getElementsByTagName("ecs:Person").item(j).getChildNodes().item(1).getTextContent()
}

But as you can see, for second person node..as "ecs:abc" is not present so "ecs:def" will be at 0th position. 但是正如您所看到的,对于第二人称节点。.由于“ ecs:abc”不存在,因此“ ecs:def”将位于第0位。 So is there any way by which I can get the child nodes by Name not by position for respective "ecs:Person" node? 那么,有什么方法可以按名称而不是按位置获取各个“ ecs:Person”节点的子节点?

1 look for getElementsByTagName("ecs:Person") 1查找getElementsByTagName(“ ecs:Person”)

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

NodeList nList = d.getElementsByTagName("ecs:Person");

for (int temp = 0; temp < nList.getLength(); temp++) 
    {
    Node nNode = nList.item(temp);
    if (nNode.getNodeType() == Node.ELEMENT_NODE)
       {
       Element eElement = (Element) nNode;

Dont use index 0, 1 , ... 不要使用索引0、1 ...

2 inside each one, look for getElementsByTagName("ecs:def") 每个内部2个,查找getElementsByTagName(“ ecs:def”)

       // DO IT AGAIN: 
       eElement.getElementsByTagName("ecs:def");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM