1

I was trying to search and replace an xml tag value using DOM. For example in my XML File i have a tag named teacher and inside that tag the text says "Teacher A". What i want the program to do is search for the tag value of "Teacher A" and change it to whatever i would like. I know i can get the tag name and the item #, but the task is to search and find the specific tag so that if there was to be changes made to the program this would be universal in finding and replacing the tag.

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 File:

 <?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>
Nm Ann
  • 21
  • 1
  • 4
  • Consider using XSLT to manipulate XML, here's someone doing it: https://stackoverflow.com/questions/10430411/update-the-text-of-an-element-with-xslt-based-on-param – Philipp Reichart Apr 05 '18 at 15:03
  • The Java code you've shown us seems to bear little relationship to the task you describe: what is its relevance? But as @PhilippReichart says, this is so much easier to do in XSLT. – Michael Kay Apr 05 '18 at 15:44

1 Answers1

0

You can use 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();
        }
    }
}
drkunibar
  • 1,327
  • 1
  • 7
  • 7