gpt4 book ai didi

JAVA,如何在 xml 中编辑节点内的文本?

转载 作者:行者123 更新时间:2023-12-02 10:03:21 25 4
gpt4 key购买 nike

假设我有当前的 XML 文件。

<?xml version="1.0" encoding="UTF-8"?>
<config>
<apps>
<app name="app1">
<url>someUrl</url>
<username>user1</username>
<password>qwerty123</password>
</app>
<app name="app2">
<url>someUrl</url>
<username>user2</username>
<password>asdasdasd</password>
</app>
<app name="app3">
<url>someUrl</url>
<username>user3</username>
<password>123456789</password>
</app>
</apps>
</config>

我已经广泛搜索了如何将第一个密码 (qwerty123) 编辑为其他内容,然后保存文件,但我就是找不到正确的解决方案。

这里有人知道我该怎么做吗?

最佳答案

使用 DOM 解析器的示例解决方案:

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<config>\n" +
" <apps>\n" +
" <app name=\"app1\">\n" +
" <url>someUrl</url>\n" +
" <username>user1</username>\n" +
" <password>qwerty123</password>\n" +
" </app>\n" +
" <app name=\"app2\">\n" +
" <url>someUrl</url>\n" +
" <username>user2</username>\n" +
" <password>asdasdasd</password>\n" +
" </app>\n" +
" <app name=\"app3\">\n" +
" <url>someUrl</url>\n" +
" <username>user3</username>\n" +
" <password>123456789</password>\n" +
" </app>\n" +
" </apps>\n" +
"</config>";
//here use your InputStream for example from file
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());


DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();

doc.getElementsByTagName("password").item(0).getFirstChild().setNodeValue("new content");
//here use your outputStream for example file output stream
OutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(doc);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer()
.transform(xmlSource, outputTarget);
//when you replace output stream with file output stream remove this, as this line is only for debugging
System.out.println(new String(((ByteArrayOutputStream) outputStream).toByteArray()));

关于JAVA,如何在 xml 中编辑节点内的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55475130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com