【问题标题】:Search and Replace Tag Value using DOM使用 DOM 搜索和替换标签值
【发布时间】:2018-09-15 10:32:10
【问题描述】:

我试图使用 DOM 搜索和替换 xml 标记值。例如,在我的 XML 文件中,我有一个名为teacher 的标签,在该标签内,文本显示为“Teacher A”。我想让程序做的是搜索“Teacher 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>

【问题讨论】:

  • 考虑使用 XSLT 来操作 XML,有人这样做:stackoverflow.com/questions/10430411/…
  • 您向我们展示的 Java 代码似乎与您描述的任务几乎没有关系:它的相关性是什么?但正如@PhilippReichart 所说,这在 XSLT 中要容易得多。

标签: java xml dom


【解决方案1】:

你可以使用 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 1970-01-01
    • 2011-01-06
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多