解析包含XML

时间:2017-10-09 13:25:09

标签: java xml

我有一个XML文档,如下所示:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="/resources/transform.xslt"?>
<map name="response">
    <prop name="numConsumers">87</prop>
    <prop name="numOutEventsQueued">17</prop>
    <prop name="numOutEventsUnAcked">2131</prop>
    <prop name="numOutEventsSent">538108577</prop>
</map>

我将响应作为字符串获取,因此我将其解析为XML并尝试提取numConsumers(值87):

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;

        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));

        NodeList nodeList  = doc.getChildNodes();
        for(int i = 0; i < nodeList.getLength(); i++) {
            String numConsumers = nodeList.item(i).getTextContent();
        }

但问题是,当i = 0numConsumerstype="text/xsl" href="/resources/transform.xslt"i = 1时,它是连接的子节点的所有值。我究竟做错了什么?我知道当前的代码没有明确地查找我想要的节点,但此时我只是想看看我是否可以访问任何节点。

1 个答案:

答案 0 :(得分:1)

NodeList nodeList  = doc.getChildNodes();

在XML DOM中,一切都是节点。在您的案例中,文档在文档级别有两个节点,即声明节点(&#39; xml-stylesheet&#39;)和文档元素(&#39; map&#39;)。根据解析器的配置,如果在文档元素之前或之后有任何空格(和架构,你没有,允许它),你就可以得到它。

获得你的目标的方法之一是:

NodeList nodeList=doc.getDocumentElement().getElementsByTagName("prop");
for(int i=0;i<nodeList.getLength();i++{

 String number=nodeList.item(i).getFirstChild().getNodeValue();

}

注意.getFirstChild()。getNodeValue(),在XML DOM中一切都是节点,元素节点的内部内容不是节点的值,它是节点的第一个子节点,第一个的值孩子是&#39; 87&#39;或其他一些价值。