【发布时间】:2025-12-24 07:20:09
【问题描述】:
我正在尝试从作为字符串从 DB 中检索的 XML 字符串中获取嵌套的子值(无法修改此步骤)。无论我做什么,属性值都会返回为空。我需要 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>
【问题讨论】:
-
如果路径无关紧要并且您只需要
fbw元素,您可以使用getElementsByTagName("fbw")获取正确的元素。否则,您将不得不使用XPath之类的东西(请参阅@omoshiroiii答案)