[英]Java XPath API Stripping HTML Tags from Text
我目前正在使用Java XPath API從字符串中提取一些文本。
但是,此字符串通常具有HTML格式( <b>
, <em>
, <sub>
等)。 當我運行代碼時,HTML標記被剝離。 有什么辦法可以避免這種情況?
這是一個示例輸入:
<document>
<summary>
The <b>dog</b> jumped over the fence.
</summary>
</document>
這是我的代碼片段:
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
InputSource source = new InputSource(new StringReader(xml));
String output = xPath.evaluate("/document/summary", source);
這是當前輸出:
The dog jumped over the fence.
這是我想要的輸出:
The <b>dog</b> jumped over the fence.
預先感謝您的所有幫助。
一個簡單直接(但可能不是很有效)的解決方案:
/**
* Serializes a XML node to a string representation without XML declaration
*
* @param node The XML node
* @return The string representation
* @throws TransformerFactoryConfigurationError
* @throws TransformerException
*/
private static String node2String(Node node) throws TransformerFactoryConfigurationError, TransformerException {
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
final StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(writer));
return writer.toString();
}
/**
* Serializes the inner (child) nodes of a XML element.
* @param el
* @return
* @throws TransformerFactoryConfigurationError
* @throws TransformerException
*/
private static String elementInner2String(Element el) throws TransformerFactoryConfigurationError, TransformerException {
final NodeList children = el.getChildNodes();
final StringBuilder sb = new StringBuilder();
for(int i = 0; i < children.getLength(); i++) {
final Node child = children.item(i);
sb.append(node2String(child));
}
return sb.toString();
}
然后,XPath評估應返回節點而不是字符串:
Element summaryElement = (Element) xpath.evaluate("/document/summary", doc, XPathConstants.NODE);
String output = elementInner2String(summaryElement);
作為解析器的一部分,它將以XML格式讀取文本,並將節點摘要的內容分類為文本,節點,文本。 使用/ document / summary時,解析程序將返回一個字符串,該字符串由選定節點的所有后代組成。 這將為您提供文本+ node.text +文本。 這就是您丟失粗體標記的原因。 摘要內的輸入字符串應為:
包裝在CDATA標簽內部會將內容視為文本:
<document>
<summary>
<![CDATA[The <b>dog</b> jumped over the fence.]]>
</summary>
解決方案的問題是解析器將希望將其視為良好的xml結構。 如果摘要中的標簽不平衡,則會出現異常。
您的問題的解決方案是在保留節點名稱的同時遍歷元素以獲取文本數據。 這可能對您的示例有用,但是,如果標簽不平衡,它將損壞:
The <b>dog</b> jumped over <br> the fence
不要使用此解決方案在摘要標記之間解析數據。 而是使用CDATA或使用某種正則表達式在起點和終點之間獲取內容。
The <b>dog</b> jumped over the fence
從此字符串中獲取孩子。 您將有2個文本節點和1個元素節點。 相應地對待他們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.