我有以下XML:
<?xml version="1.0" encoding="UTF-8"?>
<subscriber>
<data name="quota">
<![CDATA[
<?xml version="1.0" encoding="UTF-8"?><usage><version>1</version><field name="Cid"/><field name="Time"/><field name="totalVolume">4</field><field name="inputVolume"/><field name="outputVolume"/><field name="serviceSpecific"/><field name="nextResetTime"/><field name="Type"/><field name="GrantedTotalVolume"/><field name="GrantedInputVolume"/><field name="GrantedOutputVolume"/><field name="GrantedTime"/><field name="GrantedServiceSpecific"/><field name="QuotaState"/><field name="RefInstanceId"/><field name="Name">TEST_QUOTA</field></usage>
]]>
</data>
</subscriber>
为了找到所有field
个节点,我写道:
dbuilder = dbc.newDocumentBuilder();
Document doc = dbuilder.parse(new InputSource(new StringReader(xmlString)));
NodeList nl = doc.getElementsByTagName("field");
log.debug("node list length: " + nl.getLength());
for(int i = 0 ; i < nl.getLength(); i++){
Element e = (Element)nl.item(i);
log.debug("node: " + e);
String name = e.getAttribute("name");
}
但是,NodeList
的长度为0,因此无法找到名称为field
的任何节点。我想知道是不是因为field
节点之外的元数据,如果是这样,我怎样才能访问field
节点?
答案 0 :(得分:2)
首先,您需要从初始文档中提取数据元素
Document doc = dbuilder.parse(new InputSource(new StringReader(xmlString)));
Element subscriber = (Element) doc.getElementsByTagName("subscriber").item(0);
Element data = (Element) subscriber.getElementsByTagName("data").item(0);
之后,您需要使用TextContent来解析您真正想要的文档。
Document doc2 = dbuilder.parse(new InputSource(new StringReader(data.getTextContent().trim())));
Element usage = (Element) doc2.getElementsByTagName("usage").item(0);
NodeList nl = usage.getElementsByTagName("field");