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 信息集。
添加回答
举报