Java:子节点值为空

时间:2017-11-11 15:30:19

标签: java xml

我的xml(通过Java调用Powershell命令创建):

<?xml version="1.0" encoding="UTF-8"?>
-<Objects>
    -<Object>
        <Property Name="DisplayName">Adobe AIR</Property>
        <Property Name="DisplayVersion">27.0.0.124</Property>
        <Property Name="Publisher">Adobe Systems Incorporated</Property>
        <Property Name="InstallDate"/>
    </Object>

我正在尝试将DisplayName,DisplayVersion和Publisher值转换为变量,但是返回的是null和#text值:

try {

        DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
        DocumentBuilder dB = dBF.newDocumentBuilder();
        Document doc = dB.parse(new File(filename));

        NodeList nodeList = doc.getElementsByTagName("Object");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element)node;
                System.out.println("Node " + count.toString());

                NodeList childNodeList = e.getChildNodes();
                for (int j = 0; j < childNodeList.getLength() ; j++) {
                    Node childNode = childNodeList.item(j);
                    System.out.print("Child Node Type: " + childNode.getNodeType() + " - ");
                    System.out.print("Child Element Name: " + childNode.getNodeName() + " - ");
                    System.out.println("Element Value: " + childNode.getNodeValue());
                }
                count++;    

            }
        }

此代码为我的XML文件中存在的所有123个节点返回此输出:

Node 0
Child Node Type: 3 - Child Element Name: #text - Element Value: 

Child Node Type: 1 - Child Element Name: Property - Element Value: null
Child Node Type: 3 - Child Element Name: #text - Element Value: 

Child Node Type: 1 - Child Element Name: Property - Element Value: null
Child Node Type: 3 - Child Element Name: #text - Element Value: 

Child Node Type: 1 - Child Element Name: Property - Element Value: null
Child Node Type: 3 - Child Element Name: #text - Element Value: 

Child Node Type: 1 - Child Element Name: Property - Element Value: null
Child Node Type: 3 - Child Element Name: #text - Element Value: 

我一直在寻找如何阅读格式与我一样的XML文件的示例,并且我正在努力克服我非常有限的Java知识。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

你没够深入。

您只显示子节点本身,以及它们之间的空白文本节点,而不实际查看子节点内的文本节点 - 即您感兴趣的实际文本节点。

在你的内部循环中,对于每个元素节点,你必须检索该节点的子节点,其中你会找到你正在寻找的文本

            for (int j = 0; j < childNodeList.getLength() ; j++) {
                Node childNode = childNodeList.item(j);
                NodeList subList = childNode.getChildNodes();
                for (int k = 0; k<subList.getLength(); k++)
                {
                     etc...
                }
            }