gpt4 book ai didi

java - getNodeValue() 截断 org.w3c.dom.Node 中的属性内容

转载 作者:行者123 更新时间:2023-12-01 05:09:02 30 4
gpt4 key购买 nike

我正在处理 Android,需要从 URL 获取 XML 并检索一些值。下载正常,但某些字段可能包含 HTML 实体(例如 –)。当我从 Node 类 (org.w3c.dom.Node) 调用 getNodeValue() 方法时,该值在找到 & 字符时停止,并截断字符串。

例如:

<title>Episode #56 &#8211; Heroes</title>

当我调用 getNodeValue() 时,仅返回“Episode #56”。

最佳答案

你可以尝试这样的事情

String str = "<title>Episode #56 &#8211; Heroes</title>";
str = str.replaceAll("&", "amp;");

然后尝试解析 'str' 它应该可以工作。

这里是带有 dom 解析器的纯示例实现。

public static void main(String[] args) throws XPathExpressionException {
String str = "<title>Episode #56 &#8211; Heroes</title>";
str = str.replaceAll("&", "amp;");
Document domDoc = null;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
domDoc = docBuilder.parse(bis);
} catch (Exception e) {
e.printStackTrace();
}
NodeList nlist = domDoc.getElementsByTagName("title");
//System.out.println("child count "+nlist.getLength());
System.out.println("title value = "+nlist.item(0).getTextContent());
}

关于java - getNodeValue() 截断 org.w3c.dom.Node 中的属性内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12280766/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com