我正在尝试从XML字符串中获取嵌套的子值,该XML字符串是从DB检索为字符串(无法修改此步骤)。无论我做什么,该属性值都会一直返回为null。我需要fbw和bbw标签的字符串值。
我尝试了getElementsByTagName
的每种不同组合。它们都返回null
。
String xml = "<?xml version=\"1.0\" encoding = \"UTF-8\" standalone = \"yes\"?><imageresponse><id>123</id><fbw>FWB</fbw><bbw>BBW</bbw></imageresponse>"
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
NodeList nodeList = doc.getElementsByTagName("imageresponse/fbw");```
这是xml:
<?xml version="1.0" encoding = "UTF-8" standalone = "yes"?>
<imageresponse>
<id>123</id>
<fbw>FWB</fbw>
<bbw>BBW</bbw>
</imageresponse>
答案 0 :(得分:0)
我从未亲自看到xpath与getElementsByTagName一起使用,但我见过xpath与xPath类一起使用。
XPath xPather = XPathFactory.newInstance().newXPath();
String expression = "/imageresponse/fbw";
NodeList nodeList = (NodeList) xPather.compile(expression).evaluate(doc, XPathConstants.NODESET);
如果您想同时获得fwb和bbw标签:
String expression = "/imageresponse/fbw | /imageresponse/bbw";