当节点使用JAVA具有多个值时,如何替换XML标记中的值

时间:2015-10-20 03:18:53

标签: java xml

我需要替换sEmployee和sWUnumber的值(上面以黄色突出显示)

到目前为止,我能做的是替换节点值和其他属性。但是在标签中。我似乎无法替换sEmployee和SWUnumber。我假设这些元素不是属性?

到目前为止,我所做的一切。

    DocumentBuilderFactory docFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(Constant.Path_OldXmlFile);

    // Get Employee ID, I'm getting my values in excel data so don't mind this
    String sNewEmployeeID = ExcelUtils.getCellData(iTestCaseRow,
            Constant.Personnel_NewEmployeeID);

    // Get Work Unit Number, I'm getting my values in excel data so don't mind this
    String sWorkUnitNumber = ExcelUtils.getCellData(iTestCaseRow,
            Constant.Personnel_WorkUnit);

1 个答案:

答案 0 :(得分:1)

您可以使用xPath查询您之后的节点的文档并替换它的文本内容,例如

try {
    // Load the document
    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    DocumentBuilder b = f.newDocumentBuilder();
    Document original = b.parse(...);

    // Surgically locate the node you're after
    String expression = "/SyncPersonnel/ApplicationArea/BODID";
    XPath xPath = XPathFactory.newInstance().newXPath();
    Node node = (Node) xPath.compile(expression).evaluate(original, XPathConstants.NODE);
    // Get the nodes current text content
    String value = node.getTextContent();
    System.out.println(value);

    // Replace the values
    value = value.replace("sEmployee", "BananaMan").replace("sWUnumber", "007");
    // Set the text content with the new value
    node.setTextContent(value);

    // Save the new document
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty(OutputKeys.METHOD, "xml");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource domSource = new DOMSource(original);
        StreamResult sr = new StreamResult(os);
        tf.transform(domSource, sr);

        String text = new String(os.toByteArray());
        System.out.println(text);

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

} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | DOMException exp) {
    exp.printStackTrace();
}

使用...

<?xml version="1.0" encoding="UTF-8"?>
<SyncPersonnel>
  <ApplicationArea>
    <BODID>...-nid:LSAPPS:3004::sEmployee:0?Personnel&amp;verb=Sync&amp;workunit=sWUnumber</BODID>
  </ApplicationArea>  
</SyncPersonnel>

以上代码将生成

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SyncPersonnel>
  <ApplicationArea>
    <BODID>...-nid:LSAPPS:3004::BananaMan:0?Personnel&amp;verb=Sync&amp;workunit=007</BODID>
  </ApplicationArea>  
</SyncPersonnel>