【问题标题】:getNodeValue() truncates attribute content in org.w3c.dom.NodegetNodeValue() 截断 org.w3c.dom.Node 中的属性内容
【发布时间】:2012-08-30 03:11:54
【问题描述】:

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

例如:

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

当我调用 getNodeValue() 时,只返回“第 56 集”。

【问题讨论】:

    标签: java android xml string dom


    【解决方案1】:

    你可以试试这样的东西

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

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

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

    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());
    }
    

    【讨论】:

    • 我试过了,但没用:String title = parser.getValue(e, KEY_TITLE); myObj.setTitle(title.replaceAll("&", "amp;")); // 同样的问题。
    • @Rafael 它正在工作我有一个给定的示例代码,但是它没有用 dalvic 运行时测试,但逻辑可以实现对吗?。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多