6

到目前为止,这是我的代码:

// 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)));

Input[1] 是我在 XML 中寻找的内容,而 input [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 进行硬编码。请任何将不胜感激!

4

1 回答 1

8

当您想在任何元素(不仅仅是<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);
    }
}
于 2013-05-16T04:29:57.297 回答