【问题标题】:How can I change a content value in a value inside of a xml tag attribute using javax.xml.xpath?如何使用 javax.xml.xpath 更改 xml 标记属性内的值中的内容值?
【发布时间】:2015-05-21 14:43:23
【问题描述】:

使用 JAVA 和 javax.xml.xpath 的库,如 XpathFactory 和 XpathExpression,考虑到 XPath 是:如何更改标签“value=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>

【问题讨论】:

    标签: java xml xpath xml-parsing


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2017-09-20
      • 2014-09-01
      相关资源
      最近更新 更多