更改XML特定标记的内部值

时间:2016-01-18 15:21:35

标签: java xml xpath methods tags

想象一下这个XML:

<DocumentElement>
  <PropsAndValues>
    <Name># CONFIGURATION_NODE # DO NOT DELETE THIS ROW #</Name>
    <Keywords>#</Keywords>
    <Tests>#</Tests>
    <Type>#</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>PersonSuiteTC-1</Name>
    <Keywords/>
    <Tests>Definition:"Business Process":PersonSuiteTC-1</Tests>
    <Type>HIGH</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>No Operation</Name>
    <Keywords/>
    <Tests/>
    <Type>TECH</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>Start</Name>
    <Keywords>No Operation</Keywords>
    <Tests/>
    <Type>LOW</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>Open Application</Name>
    <Keywords>No Operation</Keywords>
    <Tests/>
    <Type>LOW</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>Go To Profile Finder</Name>
    <Keywords>No Operation</Keywords>
    <Tests/>
    <Type>LOW</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>Search Person</Name>
    <Keywords>No Operation</Keywords>
    <Tests/>
    <Type>LOW</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>End</Name>
    <Keywords>No Operation</Keywords>
    <Tests/>
    <Type>LOW</Type>
  </PropsAndValues>
  <PropsAndValues>
    <Name>PersonSuiteTC-1</Name>
    <Keywords>
    Start Open Application Go To Profile Finder Search Person End
    </Keywords>
    <Tests/>
    <Type>HIGH</Type>
  </PropsAndValues>
</DocumentElement>

我需要使用此标头创建一个方法:

private static void addRelation(String kWName, String elemName) throws Exception {

}

将elemName添加到<Keywords>标记值为kwName的节点的标记<Name>

例如:

addRelation("PersonSuiteTC-1", "Add this String to <Keywords> tag"),应该转到名为“PersonSuiteTC-1”的节点,并将“将此字符串添加到标记”添加到<Keywords>标记。

最简单的方法是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

1解析您的XML。

使用它,例如:

String xml= your xml
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));

2找到您的插入点。

使用XPath,使用类似的东西:

XPath xpath = XPathFactory.newInstance().newXPath();
expression="//Name[text()='PersonSuiteTC-1']";

XPathExpression expr = xpath.compile(expression) ; 
NodeList nodes  = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

请注意,您有多个带有此文本的节点

你可以迭代:

for(int k = 0; k&lt; nodes.getLength(); k ++){

  Node nodeSegment = nodes.item(k);

3插入您的数据:

使用 createElement(),createTextNode(),appendChild()

看到:How do I append a node to an existing XML file in java

4生成你的xml:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result out = new StreamResult(new File("result.xml"));
Source in = new DOMSource(document);
transformer.transform(in, out); 

希望它有所帮助!