繁体   English   中英

如何使用Java中的XPath解析标记名称中带有&的XML?

[英]How to parse an XML that has an & in its tag name using XPath in Java?

我想解析其标签包含&XML ,例如: <xml><OC&C>12.4</OC&C></xml> 我试图逃跑&&amp; 但这并不能解决标签名称的问题(仅解决了值问题),当前我的代码引发异常,请参见下面的完整功能。

public static void main(String[] args) throws Exception
{
  String xmlString        = "<xml><OC&C>12.4</OC&C></xml>";
  xmlString = xmlString.replaceAll("&", "&amp;");
  String path             = "xml";
  InputSource inputSource = new InputSource(new StringReader(xmlString));
  try
  {
    Document xmlDocument            = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputSource);
    XPath xPath                     = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(path);

    System.out.println("Compiled Successfully.");
  }
  catch (SAXException e)
  {
    System.out.println("Error while retrieving node Path:" + path + " from " + xmlString + ". Returning null");
  }
}

嗯...我不认为这是合法的XML名称 我想考虑使用正则表达式先将OC&C替换为合法的内容,然后再对其进行解析。

它不是“ XML”。 这是非XML。 XML不允许名称中使用&号。 因此,您不能使用XML解析器成功解析它。

xml不能是任何XML元素的名称。 因此,您的XML片段永远都不会被解析。 然后,您可以尝试类似的方法。

<name><![CDATA[<OC&C>12.4</OC&C>]]></name>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM