繁体   English   中英

此Java XML解析代码有什么问题?

[英]What's wrong with this Java XML-Parsing code?

我正在尝试解析XML文件,并能够插入路径并获取字段的值。

它看起来如下:

import java.io.IOException;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class XMLConfigManager {
    private Element config = null;

    public XMLConfigManager(String file) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            Document domTree;
            DocumentBuilder db = dbf.newDocumentBuilder();
            domTree = db.parse(file);
            config = domTree.getDocumentElement();
        }
        catch (IllegalArgumentException iae) {
            iae.printStackTrace();
        }
        catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        }
        catch (SAXException se) {
            se.printStackTrace();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    public String getStringValue(String path) {
        String[] pathArray = path.split("\\|");
        Element tempElement = config;
        NodeList tempNodeList = null;
        for (int i = 0; i < pathArray.length; i++) {
            if (i == 0) {
                if (tempElement.getNodeName().equals(pathArray[0])) {
                    System.out.println("First element is correct, do nothing here (just in next step)");
                }
                else {
                    return "**This node does not exist**";
                }
            }
            else {
                tempNodeList = tempElement.getChildNodes();
                tempElement = getChildElement(pathArray[i],tempNodeList);
            }
        }    
        return tempElement.getNodeValue();
    }
    private Element getChildElement(String identifier, NodeList nl) {
        String tempNodeName = null;
        for (int i = 0; i < nl.getLength(); i++) {
            tempNodeName = nl.item(i).getNodeName();
            if (tempNodeName.equals(identifier)) {
                Element returner = (Element)nl.item(i).getChildNodes();
                return returner;
            }
        }
        return null;
    }
}

XML看起来像这样(出于测试目的):

<?xml version="1.0" encoding="UTF-8"?>
<amc>
    <controller>
        <someOtherTest>bla</someOtherTest>
        <general>
            <spam>This is test return String</spam>
            <interval>1000</interval>
        </general>
    </controller>
    <agent>
        <name>test</name>
        <ifc>ifcTest</ifc>
    </agent>
</amc>

现在我可以这样叫课了

XMLConfigManager xmlcm = new XMLConfigManager("myConfig.xml");
System.out.println(xmlcm.getStringValue("amc|controller|general|spam"));

在这里,我期望标记为spam的值,因此它将是“ This is test return String ”。 但是我越来越null

我已经尝试修复此问题好几天了,但我还是无法解决。 迭代有效,因此它到达了标记spam ,但是然后,正如我所说的,它返回null而不是文本。

这是错误还是我做错了? 为什么? :(

非常感谢您的帮助!

问候,Flo

您正在调用Node.getNodeValue() -据记录,当您在元素上调用它时,它会返回null。 您应该改为调用getTextContent() -或使用更高级别的API。

正如其他人在我之前提到的那样,您似乎正在重塑XPath的概念。 您可以将代码替换为以下内容:

javax.xml.xpath.XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
String expression = "/amc/controller/general/spam";
org.xml.sax.InputSource inputSource = new org.xml.sax.InputSource("myConfig.xml");
String result = xpath.evaluate(expression, inputSource);

另请参阅: J2SE 5.0中的XML验证和XPath评估

编辑:

使用XPath提取集合的示例:

NodeList result = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);
for (int i = 0; i < result.getLength(); i++) {
    System.out.println(result.item(i).getTextContent());
}

这里记录 javax.xml.xpath.XPath接口,并且在前面的文章中还有更多示例。

此外,还有一些用于XML操作的第三方库,您可能会发现它们更方便,例如dom4j (由duffymo建议)或JDOM 无论使用哪种库,都可以利用功能强大的XPath语言。

因为您使用的是getNodeValue()而不是getTextContent()

手动执行此操作是等待发生的意外; 可以使用内置的XPath解决方案,也可以使用@duffymo建议的第三方库。 国际海事组织(IMO)在这种情况下,重新发明不会增加价值。

我想知道为什么您不使用dom4j和内置XPath之类的库。 您正在使用非常低级的API(WC3 DOM)进行大量工作。

逐步调试,并查看该<spam>节点具有哪些子级。 您应该迅速弄清楚为什么它为空。 比这里要快。

暂无
暂无

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

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