gpt4 book ai didi

java - 使用 DOM 搜索和替换标签值

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:00 25 4
gpt4 key购买 nike

我试图使用 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>

最佳答案

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

关于java - 使用 DOM 搜索和替换标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49675122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com