使用DOM搜索和替换标记值

时间:2018-04-05 14:40:21

标签: java xml dom

我试图使用DOM搜索并替换xml标记值。例如,在我的XML文件中,我有一个名为teacher的标签,在该标签内,文本显示为"教师A"。我希望程序要做的是搜索"教师A"的标签值。并将其改为我想要的任何东西。我知道我可以获得标签名称和项目#,但任务是搜索并找到特定标签,这样如果要对程序进行更改,这将是查找和替换标签的通用。

public static void reWrite() {
    try {
        String filepath = "school.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // Get the staff element by tag name directly
        Node staff = doc.getElementsByTagName("class").item(0);

        for (int i = 0; i < 3; i++) {
            /// append a new node to second student
            Node Student1 = doc.getElementsByTagName("course").item(i);
            Element dateOfBirth1 = doc.createElement("schoolBoard");
            dateOfBirth1.appendChild(doc.createTextNode("BCS"));
            Student1.appendChild(dateOfBirth1);

        }

        // update staff attribute
        Element classElem = (Element) staff;
        Node course = classElem.getElementsByTagName("course").item(0);
        Element courseElem = (Element) course;
        Node teacher = courseElem.getAttributeNode(filepath);
        teacher.setTextContent("Mr.Theo");

        //write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (SAXException sae) {
        sae.printStackTrace();
    }
}
}

XML文件:

 <?xml version="1.0" encoding="UTF-8"?>
 <class>
 <course>
  <code>ICS4U</code>
  <description>Computer Programming, Grade 12, College</description>
  <teacher>Teacher A</teacher>
  <fileType>unmodified</fileType>
 </course>
 <course>
  <code>ENG4U1-01</code>
  <description>English, Grade 12, College</description>
  <teacher>Mr.Grabham</teacher>
  <fileType>unmodified</fileType>
 </course>
 <course>
  <code>MCV4U1-01</code>
  <description>Calculus and Vectors, Grade 12, College</description>
  <teacher>Mr.Newbury</teacher>
  <fileType>unmodified</fileType>
</course>
</class>

1 个答案:

答案 0 :(得分:0)

您可以使用XPath

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlApp {

    public static void main(String[] args) throws XPathExpressionException {
        try {
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + " <class>\n"
                    + " <course>\n"
                    + "  <code>ICS4U</code>\n"
                    + "  <description>Computer Programming, Grade 12, College</description>\n"
                    + "  <teacher>Teacher A</teacher>\n"
                    + "  <fileType>unmodified</fileType>\n"
                    + " </course>\n"
                    + " <course>\n"
                    + "  <code>ENG4U1-01</code>\n"
                    + "  <description>English, Grade 12, College</description>\n"
                    + "  <teacher>Mr.Grabham</teacher>\n"
                    + "  <fileType>unmodified</fileType>\n"
                    + " </course>\n"
                    + " <course>\n"
                    + "  <code>MCV4U1-01</code>\n"
                    + "  <description>Calculus and Vectors, Grade 12, College</description>\n"
                    + "  <teacher>Mr.Newbury</teacher>\n"
                    + "  <fileType>unmodified</fileType>\n"
                    + "</course>\n"
                    + "</class>";
            ByteArrayInputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(xmlStream);
            // Using XPath
            String xpathExpression = "/class/course/teacher[text()=\"Teacher A\"]";
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodelist = (NodeList) xpath.compile(xpathExpression).evaluate(doc, XPathConstants.NODESET);
            // Update the found nodes
            for( int i = 0; i < nodelist.getLength(); i++ ){
                Node node = nodelist.item(i);
                node.setTextContent("MR. FOO");
            }
            //write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            // Write the XML into a buffer
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(output);
            transformer.transform(source, result);

            System.out.println(new String(output.toByteArray()));
        } catch (ParserConfigurationException | TransformerException | IOException | SAXException e) {
            e.printStackTrace();
        }
    }
}