gpt4 book ai didi

java xml解析错误打印节点值

转载 作者:行者123 更新时间:2023-11-29 05:43:37 35 4
gpt4 key购买 nike

我正在尝试从远程 api 解析一些 xml,xml 的格式如下:

<django-objects version="1.0">
<object pk="13" model="ballot.poll">
<field type="CharField" name="question">wwwww</field>
<field type="DecimalField" name="budget">1</field>
<field type="CharField" name="option1"></field>
<field type="CharField" name="option2"></field>
<field type="CharField" name="option3"></field>
<field type="CharField" name="option4"></field>
<field type="CharField" name="pollType">YesNo</field>
<field type="DateField" name="startDate">2013-05-17</field>
<field type="DateField" name="endDate">2013-05-17</field>
<field type="CharField" name="targetGender">M</field>
<field type="CharField" name="targetMarital">All</field>
<field type="SmallIntegerField" name="targetMinAge">1</field>
<field type="SmallIntegerField" name="targetMaxAge">1</field>
</object>
</django-objects>

这是我的解析代码,当尝试输出节点值时出现“println needs message”异常时它崩溃了

InputStream is = new ByteArrayInputStream(msg.getBytes());

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setCoalescing(true);
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document dom = null;
try {
dom = builder.parse(is);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch blockk
e.printStackTrace();
}

org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("field");

**Log.d("number of fields: ",items.getLength());** // this outputs 13 as expected because there are 13 field elements

for (int i = 0; i < items.getLength(); i++) {

Node item = items.item(i);
**Log.d("field", item.getNodeValue());** //crash here

}

最佳答案

“元素”节点包含多个 child nodes of different types .您想要始终是第一个子节点的“文本”节点,因此您可以像这样访问它...

item.getFirstChild().getNodeValue()

或者在 Java 1.5 及更高版本中更直接,您可以调用 getTextContent()直接。

关于java xml解析错误打印节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16618300/

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