代码之家  ›  专栏  ›  技术社区  ›  Personman

Java:解析XML时忽略转义

  •  4
  • Personman  · 技术社区  · 16 年前

    我正在使用DocumentBuilder来解析XML文件。但是,项目的规范要求在文本节点中 &quot; &lt; 按字面意思返回,并且 解码为字符( " <

    之前的一个类似问题, Read escaped quote as escaped quote from xml ,得到了一个似乎是特定于Apache的答案,另一个似乎根本没有做到它所说的那样。不过,我很想被证明在这两个方面都是错的:)

      file = new File(fileName);
      DocBderFac = DocumentBuilderFactory.newInstance();
      DocBder = DocBderFac.newDocumentBuilder();
      doc = DocBder.parse(file);
    
      NodeList textElmntLst = doc.getElementsByTagName(text);
      Element textElmnt = (Element) textElmntLst.item(0);
    
      NodeList txts = textElmnt.getChildNodes(); 
      String txt = ((Node) txts.item(0)).getNodeValue();
      System.out.println(txt);
    

    我希望println()能产生

    &quot;3&gt;2&quot;
    

    而不是

    "3>2"
    

    谢谢!

    4 回复  |  直到 8 年前
        1
  •  3
  •   Bozho    16 年前

    您可以通过

     StringEscapeUtils.escapeXml(str);
    

    ( javadoc , commons-lang

        2
  •  2
  •   Stefan van den Akker Raymond Hettinger    9 年前

    &quot; &lt; 按字面意思返回,而不是解码为字符(“and<)。

    不好的要求。别那么做。

    或者至少仔细想想为什么你认为你想要或需要它。

        3
  •  1
  •   John    16 年前

    一种方法可能是尝试 dom4j ,并使用 Node.asXML()

        4
  •  -3
  •   Personman    16 年前

    编辑:我知道这有各种各样的问题,而且这个要求很愚蠢。这是一个学校的项目,重要的是它在一个案例中工作,要求不是我的错:)

    推荐文章