ノードの値をリセットしようとしていますが、何らかの理由で変更が反映されていません。タグを取得しました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
れ、はのsetTextContent
メソッドNode
です。更新する必要があるのは最初の子ノードです。これは通常、要素のテキスト値ですが、確認のために検証を追加する必要があります。次に、テキスト値を更新したら、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;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加