【问题标题】:How to parse an XML that has an & in its tag name using XPath in Java?如何使用 Java 中的 XPath 解析其标记名称中包含 & 的 XML?
【发布时间】:2013-01-29 15:06:04
【问题描述】:

我想解析一个XML,其标签包含&,例如:<xml><OC&C>12.4</OC&C></xml>。我试图将& 转义为&,但这并没有解决标签名称的问题(它仅修复了值),目前我的代码正在抛出异常,请参阅下面的完整函数。

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 的脚本,只需将 添加到标签名称
  • 其实你的XML是无效的,阅读this

标签: java xpath xml-parsing


【解决方案1】:

嗯...我不认为是a legal XML name。我会考虑使用正则表达式先将 OC&C 替换为合法的,然后再解析它。

【讨论】:

  • 关于使用正则表达式处理 XML,请参见:stackoverflow.com/questions/1732348/…
  • @Arian 我不认为 Arawak 建议他使用正则表达式 parse 文档。他建议进行搜索和替换,正则表达式非常适合。然后用xml解析器解析。
  • 如果不解析 XML 文档,您将无法安全地搜索和替换它。
【解决方案2】:

它不是“XML”。这是一个非 XML。 XML 不允许在名称中使用与号。因此,您无法使用 XML 解析器成功解析它。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多