2 回答

TA貢獻1966條經驗 獲得超4個贊
XPath 使這變得簡單:
public static void main(String... args)
throws Exception
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
// Find word elements with ExposureSentence attribute
XPathExpression query = xpath.compile("//word[@ExposureSentence]");
NodeList words = (NodeList) query.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < words.getLength(); i++) {
// Remove the attribute
((Element) words.item(i)).removeAttribute("ExposureSentence");
}
// Handle ComponentName
query = xpath.compile("//ComponentName");
NodeList componentNames = (NodeList) query.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < componentNames.getLength(); i++) {
String content = componentNames.item(i).getTextContent();
componentNames.item(i).setTextContent(
Arrays.stream(content.split(","))
.map(String::trim)
.filter(s -> !s.equals("ExposureSentence"))
.collect(Collectors.joining(", ")));
}
// Omitted: Save the XML
}

TA貢獻1798條經驗 獲得超7個贊
我認為最簡單的解決方案是ExposureSentence="1"
使用簡單的正則表達式替換所有出現的情況。將所有 xml 內容讀取為 String,并替換所有不需要 XML 解析和替換的特定單詞出現位置。
在 XML 解析的情況下,您需要解析、操作邏輯,并且必須重建 XML 信息集。
添加回答
舉報