簡體   English   中英

如何在Java中使用xpath在xml中查找節點值或屬性並將其替換為其他值?

[英]How do I use xpath in Java to find a node value or attribute in an xml and replace it with another value?

這是我的代碼到目前為止:

// locate the node(s)
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate("//root[text()='input[1]']", doc, XPathConstants.NODESET);

// make the change
for (int idx = 0; idx < nodes.getLength(); idx++) {
    nodes.item(idx).setTextContent(input[3]);
}

// save the result
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));

輸入[1]是我在XML中尋找的東西,輸入[3]就是它被替換的內容。

這是XML:

<root> 
    <accounts> 
        <account name="Bill Gates">
            <position>CEO</position> 
            <phoneNumber>123-485-1854</phoneNumber>
            <notes>Runs the company</notes> 
        </account> 
        <account name="Service Account"/> 
        <account name="Burt Mackland"> 
            <position>CFO</position> 
            <phoneNumber>345-415-4813</phoneNumber> 
            <notes>Great CFO</notes> </account> 
        <account name="Joe Smith"> 
            <position>Accountant</position>
            <reportsTo>Burt Mackland</reportsTo>
            <phoneNumber>135-118-7815</phoneNumber> 
            <notes>Must have ID checked at all Gates</notes>
        </account> 
    </accounts> 
    <departments> 
        <deparment name="Finance"> 
            <employeeCount>2</employeeCount> 
        </deparment> 
        <department name="Human Resources"> 
            <employeeCount>0</employeeCount> 
        </department> 
        <department name="Executive"> 
            <employeeCount>2</employeeCount>
        </department> 
    </departments> 
</root>

用戶可能不知道XML中的內容。 所以我不能在代碼中硬編碼Xpath。 請任何不勝感激!

由於您要在任何元素(不僅是<root> )中搜索文本,請從中更改XPath表達式

//root[text()='TEXT-TO-BE-FOUND']

//*[text()='TEXT-TO-BE-FOUND']

要查找具有相同值的所有屬性,必須使用以下XPath表達式:

//*/@*[.='TEXT-TO-BE-FOUND']

此外,由於您無法進行硬編碼,因此將TEXT-TO-BE-FOUND變量。 (注意: TEXT-TO-BE-FOUND 必須被轉義 ,它可能不包含'因為它會影響XPath表達式。)

下面的工作代碼。 它將使用輸入值替換所有元素和所有屬性:

import java.io.File;
import java.util.Scanner;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class XmlChange {

    public static void main(String argv[]) throws Exception {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type like textToFind,textToReplace: "); // type, for example CEO,Chief Executive Officer
        String next = keyboard.nextLine();

        String[] input = next.split(",");

        String textToFind = input[0].replace("'", "\\'"); //"CEO";
        String textToReplace = input[1].replace("'", "\\'"); // "Chief Executive Officer";
        String filepath = "root.xml";
        String fileToBeSaved = "root2.xml";

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

        XPath xpath = XPathFactory.newInstance().newXPath();
        // change ELEMENTS


        String xPathExpression = "//*[text()='" + textToFind + "']";
        NodeList nodes = (NodeList) xpath.evaluate(xPathExpression, doc, XPathConstants.NODESET);

        for (int idx = 0; idx < nodes.getLength(); idx++) {
            nodes.item(idx).setTextContent(textToReplace);
        }

        // change ATTRIBUTES
        String xPathExpressionAttr = "//*/@*[.='" + textToFind + "']";
        NodeList nodesAttr = (NodeList) xpath.evaluate(xPathExpressionAttr, doc, XPathConstants.NODESET);

        for(int i=0; i<nodesAttr.getLength(); i++) {
            nodesAttr.item(i).setTextContent(textToReplace);
        }
        System.out.println("Everything replaced.");

        // save xml file back
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(fileToBeSaved));
        transformer.transform(source, result);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM