XML的XML DOM解析无法从子节点获取属性 [英] Java DOM parsing of XML- can't get attributes from child-child nodes
问题描述
我正在使用Java中的DOM解析器来解析XML文档。我需要得到各种属性的值。我试图解析下列文件:
I'm trying to parse an XML document using DOM parser in java. I need to get the values of various attributes. I'm trying to parse the following document:
<?xml version="1.0" encoding="UTF-8"?>
<BirthResults>
<Results>
<Rejected>
<Reject>
<Birth Etg = "etg1"/>
<Causes>
<Cause Code = "test1" Desc = "Desc1"/>
</Causes>
</Reject>
<Reject>
<Birth Etg = "etg2"/>
<Causes>
<Cause Code = "test2" Desc = "Desc2"/>
</Causes>
</Reject>
</Rejected>
</Results>
</BirthResults>
使用以下代码:
import java.io.InputStream;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.ksoap2.serialization.SoapObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Parsers {
String Etg, Dob, Breed, Brd, Sex, EId, GdEtg, SuEtg, SiEtg, BLoc, BSLoc,
PLoc, PSLoc, Code, Desc;
static String response;
public String Birth(InputStream in) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(in);
doc.getDocumentElement().normalize();
try {
NodeList list = doc.getElementsByTagName("Reject");
int L = list.getLength();
for (int x = 0; x < L; x++) {
setNull();
Node node = list.item(x);
NodeList sublist = node.getChildNodes();
for (int y = 0; y < sublist.getLength(); y++) {
Node finNode = (Node) sublist.item(y);
if (finNode.getNodeType() == Node.ELEMENT_NODE) {
Element fin = (Element) finNode;
getAttributes(fin);
}
}
}
}catch(Exception e){}
}catch(Exception e){}
}
private void getAttributes(Element fin) {
Etg = fin.getAttribute("Etg");
Code = fin.getAttribute("Code");
System.out.println(Etg + ":" + Code);
}
}
虽然我得到Etg的值,代码和Desc被返回为空白。我假设这是因为它们嵌入在更深层次的层次上,但我不知道如何解决问题。
Whilst I get the value for Etg out, the values for Code and Desc are returned as blank. I'm assuming this is because they're embedded on a deeper 'tier' but I have no idea how to get around the problem.
非常感谢。 p>
Thanks a lot.
推荐答案
NodeList sublist = node.getChildNodes();
分配给子列表,这意味着有分配的节点:出生,导致
。 原因
节点包含子项列表,所以如果您的 finNode
是出生
元素你可以得到 Egt
attr,但如果 finNode
是导致
你必须得到孩子,然后您可以从原因的每个孩子读取代码
和 Desc
NodeList sublist = node.getChildNodes();
assigns to sublist children, it means that there are assigned nodes: Birth, Causes
. The Causes
node contains list of children, so if your finNode
is Birth
element you can get Egt
attr, but if finNode
is Causes
you have to get children and then you can read Code
and Desc
from each children of 'Causes'.
对于检查元素的名称,您可以使用 fin.getTagName()
For checking name of element you can use fin.getTagName()
这篇关于XML的XML DOM解析无法从子节点获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!