【问题标题】:Get the Node value for the first Node获取第一个节点的节点值
【发布时间】:2011-09-07 23:19:46
【问题描述】:

我有以下 XML:

<?xml version='1.0' ?>
<foo>A&gt;B</foo>

只想获取起始标签的节点值为A&amp;gt;B,如果我们使用getNodeValue,它会将其转换为不需要的A>B。

因此我决定使用 Transformer

        Document doc = getParsedDoc(abovexml);
        TransformerFactory tranFact = TransformerFactory.newInstance();
        Transformer transfor = tranFact.newTransformer();
        transfor.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source src = new DOMSource(node);
        StringWriter buffer = new StringWriter();
        Result dest = new StreamResult(buffer);
        transfor.transform(src, dest);
        String result = buffer.toString();

但这会将以下输出作为结果的一部分提供为&lt;foo&gt;A&amp;gt;B&lt;/foo&gt;

如果有人能澄清一下,如果有一种方法可以让我们在不从上述输出中进行字符串操作 (&lt;foo&gt;A&amp;gt;B&lt;/foo&gt;) 的情况下获得 A&amp;gt;B,那将会很有帮助

【问题讨论】:

  • 请添加标签以识别您使用的语言和平台。
  • node 定义在哪里?

标签: java xml


【解决方案1】:

实际上 getNodeValue() 并没有“转换”字符串。 当从文件解析 XML 或通过转换生成 XML 时,生成的信息模型是字符串 A&amp;gt;B,而不是 A&amp;gt;B。后者只是一种序列化形式。

另一种合法的序列化形式是A&amp;gt;B(因为right angle bracket does not need to be escaped in most cases)。但是,想要生成 A&amp;gt;B 可能存在兼容性原因,尤其是当您的输出是 HTML 时(尽管您没有提及)。

如果您有充分的理由逃避&gt;,那么我同意@kensen john 的回答。

【讨论】:

    【解决方案2】:

    由于 getNodeValue() 会自动解码字符串。
    您可以使用 Apache Commons Lang 中的 StringEscapeUtils 再次对其进行编码。

    http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringEscapeUtils.html
    http://commons.apache.org/lang/

    String nodeValue = StringEscapeUtils.escapeHtml(getNodeValue());
    

    这会将其编码为您想要的格式。 它对性能不太友好,因为您正在为每个节点值应用编码。

    【讨论】:

    • 实际上,getNodeValue() 没有解码字符串。字符串在解析时被解码。在信息模型中,可以推测它是如何存储在内存中的,字符串 A&amp;gt;B,而不是A&amp;gt;B。后者只是一种序列化形式。 getNodeValue() 返回实际字符​​串 A&amp;gt;B。但是这里给出的解决方案是正确的:如果你想要一个转义形式 (A&amp;gt;B),你需要请求它,例如使用转义实用程序。
    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2023-03-30
    • 2013-08-10
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多