[英]Dom parsing xml problems
我有一個簡單的.xml
文件,需要對其進行解析。 該文件如下:
<table name="agents">
<row name="agent" password="pass" login="agent" ext_uid="133"/>
</table>
我需要獲取name, password, login, ext_uid
才能創建數據庫記錄。
為此我做了什么:創建了一個or.w3c.dom.Document
:
public Document getDocument(String fileName){
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setValidating(false);
DocumentBuilder builder = f.newDocumentBuilder();
return builder.parse(new File(fileName));
}
接下來,我嘗試打印值:
document = getDocument(fileName);
NodeList nodes = document.getChildNodes();
for (int i=0; i<nodes.getLength(); i++){
Node node = nodes.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE){
NodeList listofNodes = node.getChildNodes();
for(int j=0; j<listofNodes.getLength(); j++){
if(node.getNodeType() == Node.ELEMENT_NODE){
Node childNode = listofNodes.item(j);
System.out.println(childNode.getNodeValue()+" " + childNode.getNodeName());
}
}
}
}
我使用它是因為我試圖找出如何獲取值: childNode.getNodeValue()+" " + childNode.getNodeName()
但結果如下:
#text
null row
#text
在第一種和第三種情況下,NodeValue為空,在第二種情況下為null,這意味着我想根本就沒有NodeValue。 所以我的問題是如何獲取name, password, login, ext_uid
?
childNode.getNodeValue()顯然為null,因為其為空標簽。 您必須尋找屬性
Node childNode = listofNodes.item(j);
Element e = (Element)childNode;
String name = e.getAttribute("name");
String password= e.getAttribute("password");
String login= e.getAttribute("login");
String ext_uid= e.getAttribute("ext_uid");
<row>
元素沒有值,僅具有屬性。 如果它具有值,則它看起來更像<row>this would be the value returned from getNodeValue()</row>
。
獲取數據的一種方法是迭代XML節點屬性,例如:
NamedNodeMap attrs = childNode.getAttributes();
if (attrs != null) {
for (int k = 0; k < attrs.getLength(); k++) {
System.out.println("Attribute: "
+ attrs.item(k).getNodeName() + " = "
+ attrs.item(k).getNodeValue());
}
}
由於示例XML文件中的回車符( \\n
字符),因此代碼的輸出顯示為#text
,根據規范應將其保留。 示例輸出中的null
是無值<row>
元素中的空節點值。
改用XPath:
XPath xp = XPathFactory.newInstance().newXPath();
System.out.println(xp.evaluate("/table/row/@name", doc));
System.out.println(xp.evaluate("/table/row/@password", doc));
System.out.println(xp.evaluate("/table/row/@login", doc));
System.out.println(xp.evaluate("/table/row/@ext_uid", doc));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.