【发布时间】:2013-01-29 15:06:04
【问题描述】:
我想解析一个XML,其标签包含&amp;,例如:<xml><OC&C>12.4</OC&C></xml>。我试图将&amp; 转义为&amp;,但这并没有解决标签名称的问题(它仅修复了值),目前我的代码正在抛出异常,请参阅下面的完整函数。
public static void main(String[] args) throws Exception
{
String xmlString = "<xml><OC&C>12.4</OC&C></xml>";
xmlString = xmlString.replaceAll("&", "&");
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