Java 更改XML特定标记的内部值
想象一下这个XML:Java 更改XML特定标记的内部值,java,xml,xpath,methods,tags,Java,Xml,Xpath,Methods,Tags,想象一下这个XML: <DocumentElement> <PropsAndValues> <Name># CONFIGURATION_NODE # DO NOT DELETE THIS ROW #</Name> <Keywords>#</Keywords> <Tests>#</Tests> <Type>#</Type> </Pro
<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>
将elemName添加到具有标记值kwName的节点的标记
例如:
String xml= your xml
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
addRelation(“personsuitec-1”,“将此字符串添加到标记”)
应转到名为“personsuitec-1”的节点,并将“将此字符串添加到标记”添加到
标记
最简单的方法是什么
谢谢。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);
请注意,您有多个包含此文本的节点
您可以迭代:
对于(int k=0;kTransformer transformer = TransformerFactory.newInstance().newTransformer();
Result out = new StreamResult(new File("result.xml"));
Source in = new DOMSource(document);
transformer.transform(in, out);
使用createElement()、createTextNode()、appendChild()
请注意:
4生成xml返回:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result out = new StreamResult(new File("result.xml"));
Source in = new DOMSource(document);
transformer.transform(in, out);
希望能有所帮助!如果有问题要求我们推荐或查找书籍、工具、软件库、教程或其他非网站资源,则会导致堆栈溢出,因为这些问题往往会吸引自以为是的答案和垃圾邮件。相反,请描述问题以及迄今为止为解决此问题所做的工作。