繁体   English   中英

使用DOM解析器解析XML字符串返回null

[英]Parsing XML string using DOM parser returns null

我正在尝试从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>

我从未亲自看到xpath与getElementsByTagName一起使用,但我见过它与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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM