我正在尝试使用 java 中的 DOM 解析器解析 XML 文档。我需要获取各种属性的值。我正在尝试解析以下文档:
<?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 out 的值,但 Code 和 Desc 的值返回为空白。我假设这是因为它们嵌入了更深的“层”,但我不知道如何解决这个问题。
非常感谢。