gpt4 book ai didi

android - 嵌套的xml解析使用dom解析

转载 作者:行者123 更新时间:2023-11-29 00:33:30 25 4
gpt4 key购买 nike

My xml is as follows...In this how can I get NAME attribute from status tag using DOM xml   
parsing...

<tickets type="array">
<ticket>
<ticket-id type="integer">6</ticket-id>
<status>
<id type="integer">1706729</id>
<name>Completed</name>
<colour>black</colour>

</status>
</ticket>

<ticket>
<ticket-id type="integer">5</ticket-id>
<status>
<id type="integer">1706929</id>
<name>New</name>
<colour>White</colour>

</status>
</ticket>
</tickets>

最佳答案

这样你应该能够得到你正在寻找的东西

String xml = "<tickets type=\"array\"><ticket><ticket-id type=\"integer\">6</ticket-id><status><id type=\"integer\">1706729</id><name>Completed</name><colour>black</colour></status></ticket><ticket><ticket-id type=\"integer\">5</ticket-id><status><id type=\"integer\">1706929</id><name>New</name><colour>White</colour></status></ticket></tickets>";
Log.e("xml parsing ", xml);
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
domFactory.setIgnoringComments(true);
domFactory.setIgnoringElementContentWhitespace(true);
domFactory.setCoalescing(true);
DocumentBuilder domBuilder = null;
Document document = null;

try {
domBuilder = domFactory.newDocumentBuilder();
}
catch (ParserConfigurationException parserConfigurationException) {
Logger.log(Logger.LEVEL_ERROR, FrameworkHelper.class.getName(), "getDocumentRoot", "ParserConfigurationException caught while creating DocumentBuilder object, " + parserConfigurationException.getMessage());
}

document = domBuilder.parse(new ByteArrayInputStream(xml.getBytes()));//try catch
NodeList ticketList = document.getElementsByTagName("ticket");
for (int i = 0; i < ticketList.getLength(); i++) {
Element ticketNode = (Element) ticketList.item(i);
String tickets = ticketNode.getNodeValue();
NodeList statusList = ticketNode.getElementsByTagName("status");
for (int j = 0; j < statusList.getLength(); j++) {
Element statusNode = (Element) statusList.item(j);
String statuses = statusNode.getNodeValue();
NodeList nameList = statusNode.getElementsByTagName("name");
for (int k = 0; k < nameList.getLength(); k++) {
Element nameNode = (Element) nameList.item(k);
String names = nameNode.getChildNodes().item(0).getNodeValue();
Toast.makeText(this, "name: " + names,
Toast.LENGTH_SHORT).show();
}
}
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

但是如果维护层次结构并不重要,而您只想独立处理名称,您也可以直接调用 getElementsByTagName("name")

关于android - 嵌套的xml解析使用dom解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14018257/

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