[英]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>
。 我試圖逃跑&
來&
但這並不能解決標簽名稱的問題(僅解決了值問題),當前我的代碼引發異常,請參見下面的完整功能。
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名稱 。 我想考慮使用正則表達式先將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.