简体   繁体   English

解析包含XML的字符串后,XML Document为空

[英]XML Document is null after parsing string containing XML

I have an XML document that looks like this: 我有一个看起来像这样的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>

I get the response as a string, so I parse it to XML and try to extract numConsumers (the value 87): 我将响应作为字符串获取,因此我将其解析为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();
        }

But the thing is, when i = 0 , numConsumers is type="text/xsl" href="/resources/transform.xslt" and when i = 1 , it is all the values of the child nodes, concatenated. 但是问题是,当i = 0numConsumerstype="text/xsl" href="/resources/transform.xslt"而当i = 1 ,则是所有子节点的值(级联)。 What am I doing wrong? 我究竟做错了什么? I'm aware that the current code is not explicitly looking for the node I want, but at this point I'm just trying to see if I can get to any of the nodes. 我知道当前代码没有明确寻找我想要的节点,但是在这一点上,我只是想看看是否可以访问任何节点。

NodeList nodeList  = doc.getChildNodes();

In XML DOM everything is a node. 在XML DOM中,一切都是节点。 The document in your case has 2 nodes at document level the declaration node ('xml-stylesheet') and the document element ('map'). 在您的情况下,文档在文档级别有2个节点,即声明节点('xml-stylesheet')和文档元素('map')。 Depending on the configuration of the parser, if there are any white spaces (and schema , which you dont have, allows it) before or after document element, you would have got that. 根据解析器的配置,如果在文档元素之前或之后有任何空白(以及没有的架构,则允许它),您将已经知道。

One of the way to get what you are at is the below: 获得自我的一种方法如下:

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

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

}

Notice the .getFirstChild().getNodeValue(), in XML DOM everything is a node, internal content of an element node is not the value of the node, it is the first child of the node, the value of the first child is '87' or some other value. 注意.getFirstChild()。getNodeValue(),在XML DOM中,所有内容都是一个节点,元素节点的内部内容不是该节点的值,它是该节点的第一个子节点,第一个子节点的值是' 87'或其他值。

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

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