繁体   English   中英

如何使用javax.xml.xpath在xml标记属性内的值中更改内容值?

[英]How can I change a content value in a value inside of a xml tag attribute using javax.xml.xpath?

使用JAVA和javax.xml.xpath的库(作为XpathFactory和XpathExpression),考虑到XPath是:如何更改标记“值= 6”的xml标记属性“ 6”:

"number(/suite/test/classes/class/methods/include/parameter[1]/@value)"

xPathFactory可以识别xpath函数吗? 还是有其他想法?

以下XML进行更改:

<?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>

您可以使用DOM解析器在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM