如何在Java中更新xml中的多个节点

如何在Java中更新xml中的多个节点,java,xml,transformation,nodelist,Java,Xml,Transformation,Nodelist,我正在尝试使用nodelist更新xml中的多个节点。我能够做到这一点,但我认为我的代码效率不高。为了更新两个节点,我将重复我的代码两次。我不知道如何循环。我从for循环中尝试了它,或者尝试将它变成一个arraylist和所有东西,但它根本不起作用 这是我的密码: String expressionDisclosure = "/DOCUMENT/ishobject/ishfields/ishfield[@name='FHPIDISCLOSURELEVEL']"; String expressio

我正在尝试使用nodelist更新xml中的多个节点。我能够做到这一点,但我认为我的代码效率不高。为了更新两个节点,我将重复我的代码两次。我不知道如何循环。我从for循环中尝试了它,或者尝试将它变成一个arraylist和所有东西,但它根本不起作用

这是我的密码:

String expressionDisclosure = "/DOCUMENT/ishobject/ishfields/ishfield[@name='FHPIDISCLOSURELEVEL']";
String expressionLanguage = "/DOCUMENT/ishobject/ishfields/ishfield[@name='DOC-LANGUAGE']";

String key = "";
String value = "";
try {
    DocumentBuilderFactory documentbuilderfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentbuilder = documentbuilderfactory.newDocumentBuilder();
    Document doc = documentbuilder.parse(filepath);
    XPath xPath = XPathFactory.newInstance().newXPath();


    Node updateNode = null;

    NodeList nodelistLanguage = (NodeList) xPath.evaluate(expressionLanguage,
            doc.getDocumentElement(), XPathConstants.NODESET);
    NodeList nodelistDisclosure = (NodeList) xPath.evaluate(expressionDisclosure,
            doc.getDocumentElement(), XPathConstants.NODESET);

    key = nodelistLanguage.item(0).getTextContent();
    if (key != null) {
        value = getHashmap().get(key);
        updateNode = nodelistLanguage.item(0);
        updateNode.setTextContent(value);
    }


    key = nodelistDisclosure.item(0).getTextContent();
    if (key != null) {
        value = getHashmap().get(key);
        updateNode = nodelistDisclosure.item(0);
        updateNode.setTextContent(value);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StreamResult stream = new StreamResult(new File(filepath));
    transformer.transform(source, stream);


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

我正在更新节点两次。这是正确的方法还是更有效?

必须将实际进行更改的代码移动到方法中,并提供要更改的节点路径作为该方法的参数。然后,您将根据需要多次调用该方法(甚至提供一个节点列表作为参数),您必须将实际进行更改的代码移动到一个方法,并提供要更改的节点的路径作为该方法的参数。然后,您可以根据需要多次调用该方法(甚至可以提供一个节点列表作为参数)