使用JAVA和javax.xml.xpath的库,作为XpathFactory和XpathExpression,如何考虑XPath是:
,如何更改标记“value = 6”的xml标记属性“6”"number(/suite/test/classes/class/methods/include/parameter[1]/@value)"
xPathFactory是否识别xpath函数?还是有其他想法?
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Test1" Alowinterrupt="true">
<test name="testscale">
<classes>
<class name="test">
<methods>
<include name="poweronoff">
<parameter name="ScaleTesting" value="6"/>
</include>
</methods>
</class>
</classes>
</test>
</suite>
答案 0 :(得分:0)
您可以使用DOM parser在Java中修改XML文件。
// parse the XML as a W3C Document
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.parse(new File(xmlFilePath));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/suite/test/classes/class/methods/include/parameter[1]";
Node parameter = (Node) xpath.evaluate(expression, document,
XPathConstants.NODE);
// update parameter , set the value to 10
NamedNodeMap attribute = parameter.getAttributes();
Node nodeAttr = attribute.getNamedItem("value");
System.out.println("Old id value: " + nodeAttr.getTextContent());
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
Result output = new StreamResult(new File(xmlFilePath));
nodeAttr.setTextContent("2");
Source input = new DOMSource(document);
transformer.transform(input, output);
System.out.println("New id value: " + nodeAttr.getTextContent());
输出:
Old parameter value: 6
New parameter value: 2