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

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

 

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

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

给出一个示例XML:

            

为了改变2个标记!Here ,你需要

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

  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))); 

生成的XML文件是: