gpt4 book ai didi

java - 如何使用java更改XML节点的值?

转载 作者:行者123 更新时间:2023-12-02 11:31:41 25 4
gpt4 key购买 nike

我试图重置节点的值,但由于某种原因,更改没有反射(reflect)出来。我通过 XPATH 获取标签,但它没有设置我给出的值。reqXML 是 XML 文件

我的代码

public static String changeProductVersion(String reqXML) {

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = null;
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource source = new InputSource();
source.setCharacterStream(new StringReader(reqXML));
document = builder.parse(source);

XPath xPath = XPathFactory.newInstance().newXPath();
Element element = (Element) xPath.evaluate(NYPG3Constants.NY_PG3_RL, document, XPathConstants.NODE);

if(element != null) {
element.setTextContent("17.1.0");
System.out.println(element.getTextContent());
}

} catch (Exception ex) {
ex.printStackTrace();
}
return reqXML;
}

提前致谢

最佳答案

我必须做出一些假设和更改,因为我不知道您的 XML 文档是什么样子。但是,Element 类扩展了 Node,而 setTextContentNode 上的一个方法。您需要更新的是第一个子节点,它通常是元素的文本值,但您应该添加一些验证来确保。然后,一旦您更新了文本值,您需要将 DOM 序列化回其来源的任何形式:

public static String changeProductVersion(String reqXML, String xpathExpression) {

Document document = null;
String updatedXML = null;

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(reqXML));
document = builder.parse(is);

XPath xPath = XPathFactory.newInstance().newXPath();
Element element = (Element) xPath
.compile(xpathExpression)
.evaluate(document, XPathConstants.NODE);

if(element != null) {
NodeList childNodes = element.getChildNodes();

// Get the first node which should be the text value.
// Add some validation to make sure Node == Node.TEXT_NODE.
Node node = (Node) childNodes.item(0);
node.setTextContent("17.1.0");
}

System.out.println("Updated element value: " + element.getTextContent());

// Serialise the updated DOM
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);

updatedXML = result.getWriter().toString();

} catch (Exception ex) {
ex.printStackTrace();
}

System.out.println(updatedXML);
return updatedXML;
}

关于java - 如何使用java更改XML节点的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49245031/

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