【发布时间】:2017-07-12 22:11:09
【问题描述】:
所以,我有一个看起来像这样的 XML 结构。
<root xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
<actors>
<actorUID>1w2e3r</actorUID>
<actor id="1">
<name>Christian Bale</name>
<age>40</age>
</actor>
<actor id="2">
<name>LiamNeeson</name>
<age>45</age>
</actor>
<actor id="3">
<name>Michael</name>
<age>60</age>
</actor>
</actors>
<foo:singers>
<foo:singer id="4">
<name>Michael</name>
<age>60</age>
</foo:singer>
<foo:singer id="5">
<name>Michael</name>
<age>60</age>
</foo:singer>
<foo:singer id="6">
<name>Michael</name>
<age>60</age>
</foo:singer>
</foo:singers>
</root>
我需要解析这个json并将actorUID、actor.name、actor.age、foo:singers.name、foo:singers.age的元素保存到数据库中。
我试过这个:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(stops));
Document doc = db.parse(is);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/root/actors");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
Element element = (Element) nl.item(i);
System.out.println(element.getElementsByTagName("actorsUID")
.item(0)
.getTextContent());
System.out.println(element.getElementsByTagName("actor")
.item(0)
.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
我得到这个后如何获得演员姓名 - element.getElementsByTagName("actor")
?
我不想只获取 name 元素,因为如果我必须将另一个子元素添加到演员,并且如果它有 actor.name,那么它会中断。
【问题讨论】: