简体   繁体   English

如何使用DOM API访问XML节点的值

[英]how can I access the values of XML nodes using DOM API

I am trying to access some values in an XML document with Dom parser and I am getting a strange null pointer exception error. 我正在尝试使用Dom解析器访问XML文档中的某些值,并且出现了一个奇怪的空指针异常错误。 the code I am using is: 我使用的代码是:

    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;

    public class readXML {

    public static void main(String[] args) {
    File file = new File("C:\\Users\\manolaki\\Desktop\\assets.xml");
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = builder.parse(file);
      doc.getDocumentElement().normalize();

            Node node = doc.getElementsByTagName("assets").item(0).getChildNodes().item(1).getChildNodes().item(1).getAttributes().getNamedItem("src");

            String boo = node.getNodeValue();

            System.out.println("Name is " + boo);

      }
    catch (Exception e) {
      e.printStackTrace();
      }
   }
}

the xml I am Using: 我正在使用的xml:

 <?xml version="1.0" encoding="UTF-8"?>
<xml>

<assets>
<sprite>
    <img src="menu.png"/>
</sprite>
<sprite>
    <img src="background.png"/>
</sprite>
<sprite>
    <img src="buttons.png"/>
</sprite>
<sprite>
    <img src="animals.png"/>
</sprite>
<sprite>
    <img src="cycles.png"/>
</sprite> 
<sprite>
    <img src="texts.mp3"/>
</sprite>
<sprite>
    <img src="music.mp3"/>
</sprite>
<sprite>
    <img src="click.mp3"/>
</sprite>
<sprite>
    <img src="swipe.mp3"/>
</sprite>
<sprite>
    <img src="dog.mp3"/>
</sprite>
</assets>

<assets>
<sprite>
    <img src="mehnu.png"/>
</sprite>
<sprite>
    <img src="background.png"/>
</sprite>
<sprite>
    <img src="buttons.png"/>
</sprite>
<sprite>
    <img src="animals.png"/>
</sprite>
<sprite>
    <img src="cycles.png"/>
</sprite> 
<sprite>
    <img src="texts.mp3"/>
</sprite>
<sprite>
    <img src="music.mp3"/>
</sprite>
<sprite>
    <img src="click.mp3"/>
</sprite>
<sprite>
    <img src="swipe.mp3"/>
</sprite>
<sprite>
    <img src="dog.mp3"/>
</sprite>
 </assets>

 </xml>

The code works fine as is and it prints out "menu.png" at the console. 该代码按原样工作正常,并在控制台上打印出“ menu.png”。 The problem is that while I can navigate through the assets nodes using the first "Item()" part, if i try to change the second "item()" to navigate through the sprites it prints a null pointer exception error. 问题是,尽管我可以使用第一个“ Item()”部分浏览资产节点,但是如果我尝试更改第二个“ item()”以浏览子画面,则会打印出空指针异常错误。 for example it works if I use: 例如,如果我使用它可以工作:

                Node node = doc.getElementsByTagName("assets").item(1).getChildNodes().item(1).getChildNodes().item(1).getAttributes().getNamedItem("src");

but not when I use 但是当我使用

            Node node = doc.getElementsByTagName("assets").item(0).getChildNodes().item(2).getChildNodes().item(1).getAttributes().getNamedItem("src");

Which I think is kind of strange.. given that eclipse is not finding any errors. 考虑到日食没有发现任何错误,我认为这有点奇怪。 any help would be appreciated. 任何帮助,将不胜感激。 thanks 谢谢

Your problem is that item(0) of the NodeList is a text node, and text nodes don't have child nodes which is where your NullPointerException is being thrown. 您的问题是NodeList的item(0)是一个文本节点,并且文本节点没有子节点,在该子节点上会抛出NullPointerException。

Try adding this to your code to verify: 尝试将其添加到您的代码中以验证:

Node child0 = doc.getElementsByTagName("assets").item(0).getChildNodes().item(0);
if (child0.getNodeType() == Node.TEXT_NODE) {
    System.out.println("child node is text");
}

So just keep in mind that you need to check the type of each node when iterating through a NodeList. 因此,请记住,在遍历NodeList时需要检查每个节点的类型。

In your case, your odd numbered children are text nodes and your even children are elements. 在您的情况下,您的奇数子代是文本节点,而偶数子代是元素。 Try this: 尝试这个:

NodeList nodes = doc.getElementsByTagName("assets").item(0).getChildNodes();
for ( int x = 0; x < nodes.getLength(); x++ ) {
    Node node = nodes.item(x);
    if (node.getNodeType() == Node.TEXT_NODE) {
        System.out.println(x + " text");
    } else if (node.getNodeType() == Node.ELEMENT_NODE) {
        String nodeName = node.getNodeName();

        System.out.println(x + " Node: " + nodeName);
    }
}

Output: 输出:

0 text
1 Node: sprite
2 text
3 Node: sprite
4 text
5 Node: sprite
...

You might want to check out this article from Dr. Dobb's which has some good example code from which you could create some convenience methods for low level DOM parsing like this. 您可能想看看Dobb博士的这篇文章 ,其中有一些很好的示例代码,您可以从中创建一些方便的方法来进行此类低级DOM解析。

For a simpler API check out Xsylum . 有关更简单的API,请查看Xsylum Using the DOM: 使用DOM:

String src = Xsylum.elementFor(xmlFile).get("sprite").get("img").attribute("src");

Or using XPath: 或使用XPath:

String src = Xsylum.elementFor(xmlFile).value("//sprite[1]/img/@src");

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

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