如何在XML中查找和替换属性值

Enz*_*nzo 6 java xml dom

我正在Java中构建一个"XML扫描程序",它找到以"!Here:"开头的属性值.属性值包含稍后要替换的指令.例如,我有这个xml文件填充像记录

<bean value="!Here:Sring:HashKey"></bean>
Run Code Online (Sandbox Code Playgroud)

我怎样才能找到并替换属性值,只知道它的开头"!Here:"

T.G*_*lle 15

为了修改XML文件中的某些元素或属性值,在仍然尊重XML结构的同时,您需要使用XML解析器.它只涉及String$replace()......

给出一个示例XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans> 
    <bean id="exampleBean" class="examples.ExampleBean">
        <!-- setter injection using -->
        <property name="beanTwo" ref="anotherBean"/>
        <property name="integerProperty" value="!Here:Integer:Foo"/>
    </bean>
    <bean id="anotherBean" class="examples.AnotherBean">
        <property name="stringProperty" value="!Here:String:Bar"/>
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

要更改2个标记!Here,您需要

  1. 将文件加载到dom中Document,
  2. 用xpath选择想要的节点.在这里,我使用value包含字符串的属性搜索文档中的所有节点!Here.xpath表达式是//*[contains(@value, '!Here')].
  3. 在每个选定的节点上进行所需的转换.在这里,我只是改变!HereWhat?.

  4. 将修改后的dom保存Document到新文件中.


static String inputFile = "./beans.xml";
static String outputFile = "./beans_new.xml";

// 1- Build the doc from the XML file
Document doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(new InputSource(inputFile));

// 2- Locate the node(s) with xpath
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate("//*[contains(@value, '!Here')]",
                                          doc, XPathConstants.NODESET);

// 3- Make the change on the selected nodes
for (int idx = 0; idx < nodes.getLength(); idx++) {
    Node value = nodes.item(idx).getAttributes().getNamedItem("value");
    String val = value.getNodeValue();
    value.setNodeValue(val.replaceAll("!Here", "What?"));
}

// 4- Save the result to a new XML doc
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
Run Code Online (Sandbox Code Playgroud)

生成的XML文件是:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans> 
    <bean class="examples.ExampleBean" id="exampleBean">
        <!-- setter injection using -->
        <property name="beanTwo" ref="anotherBean"/>
        <property name="integerProperty" value="What?:Integer:Foo"/>
    </bean>
    <bean class="examples.AnotherBean" id="anotherBean">
        <property name="stringProperty" value="What?:String:Bar"/>
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

  • 多么详细的API! (6认同)