gpt4 book ai didi

java - 解析包含 XML 的字符串后,XML 文档为 null

转载 作者:行者123 更新时间:2023-12-02 12:09:32 24 4
gpt4 key购买 nike

我有一个如下所示的 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 = 0 时,numConsumerstype="text/xsl"href="/resources/transform.xslt"i = 1时,它是所有子节点的值,连接起来。我究竟做错了什么?我知道当前的代码没有明确查找我想要的节点,但此时我只是想看看是否可以到达任何节点。

最佳答案

NodeList nodeList  = doc.getChildNodes();

在 XML DOM 中,一切都是节点。您的案例中的文档在文档级别有 2 个节点:声明节点(“xml-stylesheet”)和文档元素(“map”)。根据解析器的配置,如果文档元素之前或之后有任何空格(以及您没有的 schema 允许它),您就会得到它。

获取当前信息的方法之一如下:

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中一切都是节点,元素节点的内部内容不是节点的值,而是节点的第一个子节点,第一个的值child 是“87”或其他值。

关于java - 解析包含 XML 的字符串后,XML 文档为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46647589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com