In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shares with you the content of the sample analysis of JAXP in XML. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
According to a CRUD case, the JAXP parsing xml technology is explained in detail:
First, it is known that the data in a xml file is as follows:
Java Zhang Zehua 39.00 yuan JavaScript web page developer Li Honglei 28.00 yuan
Then according to the form of the unit test, the CRUD is written in a test framework method. To facilitate testing the correctness of the code.
Package com.itheima.dom;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.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.TransformerFactoryConfigurationError;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import junit.framework.Assert;import org.junit.Test;import org.w3c.dom.Document Import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;/* use xml dom to CRUD xml files * 1. Read the text content of the node 2. Read the attribute value 3. Add node 4. Delete node 5. Update node 6. Print the names of all element nodes. Protected method, do not let the new object * * / public class TestDomExercises {/ / read the text content of the node: Java Employment training tutorial @ Test public void testReadContent () throws Exception {/ / Test Framework exception needs to be thrown / / to get the document object Document document = getDocument () that represents the xml file / / list of nodes whose name is obtained from the tag signature NodeList nl= document.getElementsByTagName ("title of the book"); int length = nl.getLength (); System.out.println ("length:" + length) / / returns the first title node Node firstBookNameNode = nl.item (0); String result = firstBookNameNode.getTextContent (); / / String getTextContent () this property returns the text content of this node and its descendants. Assert.assertEquals ("Java", result);} / 2. Read attribute value: publishing house = "Shenzhen Publishing House 1" @ Test public void testReadAttribute () throws Exception {/ / get document object Document document = getDocument (); NodeList nl = document.getElementsByTagName ("book") / / get the node object of the first book / / Node firstBookNode = nl.item (0) / Note: after looking at api here, it is found that there is no method to get attribute value based on attribute name in Node. The element element has a direct method of [getting the attribute value according to the attribute name], and what you get here is actually / / an element Node node, so here you think of casting to the element Element. Then get the value of the property according to the property name of his method / / get the first book / / nl.item (0) and return the Node object Transform down to an Element object. Because there is a method in Element to find value directly based on the element: getAttribute ("publisher"); get the value of the attribute by name Element firstBookElement = (Element) nl.item (0); / / String getAttribute (String name) get the value of the attribute by name. String result = firstBookElement.getAttribute ("Publishing House"); / / get the attribute value Assert.assertEquals according to the attribute name (Shenzhen Publishing House 1, result);} / / 3. Add a node: RMB79.00 @ Test public void testAddPrice () throws Exception, SAXException, IOException {/ / get the document object Document document = getDocument (); / / get the first book node Node firstBookNode = document.getElementsByTagName ("book") .item (0) / / create a price node and set the text to RMB79.00 / / Element org.w3c.dom.Document.createElement (String tagName) / / Element createElement (String tagName) to create elements of the specified type. Element createPriceElement = document.createElement ("selling price"); / / createPriceElement.setTextContent ("79.00 yuan"); / / 79.00 yuan / / Node org.w3c.dom.Node.appendChild (Node newChild) firstBookNode.appendChild (createPriceElement); / / add the node newChild to the end of the list of child nodes of this node. If newChild already exists in the tree, remove it first. WriteBack2Xml (document);} / * * when you go back to write the code, if you encounter this exception: * * initializationError (org.junit.runner.manipulation.Filter) * * is that you did not add @ Test annotation * / 4. Delete the node: RMB39.00 @ Test public void testDelete () throws Exception, SAXException, IOException {/ / get the document object Document document = getDocument (); / / get the node NodeList priceNodeList = document.getElementsByTagName ("selling price"); for (int I = 0; I)
< priceNodeList.getLength(); i++) { // 拿到 每个售价节点 Node node = priceNodeList.item(i); if ("39.00元".equals(node.getTextContent())) { // 如果进来, 则说明找到 39.00元的售价节点 // 拿到当前节点的父节点, 然后 删除 这个 节点 node.getParentNode().removeChild(node); } } // 更新 到 xml 文件 writeBack2Xml(document); } // 5.更新节点 : 79.00元 ---------->> 9.9 CNY public void testUpdatePrice () {} / / 6. Print the names of all element nodes. @ Test public void testPrintAllElementsName () throws Exception, SAXException, IOException {/ / get document object Document document = getDocument (); printAllElementsName (document) } public void printAllElementsName (Node node) {if (Node.ELEMENT_NODE = = node.getNodeType ()) {/ / description is the element node System.out.println (node.getNodeName ());} NodeList childNodes = node.getChildNodes () For (int I = 0; I
< childNodes.getLength(); i++) { // 拿到 遍历过程中的 每一个 node Node item = childNodes.item(i); printAllElementsName(item); } } // 需要将内存中的document 对象 重新写回到 xml 文件中去 private void writeBack2Xml(Document document) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { // 如何弄? // 查看 文档, transformerFacotry --->> Transformer instance TransformerFactory factory = TransformerFactory.newInstance (); / / get the instance object of the converter Transformer transformer = factory.newTransformer (); / / call the conversion method to write the document object in memory to the xml file / / abstract void transform (Source xmlSource, Result outputTarget) to convert XML Source to Result. / / DOMSource happens to be the Source implementation class. And it has a constructor DOMSource (Node n) that happens to receive a Node / / Result implementation class that has a StreamResult his constructor StreamResult.StreamResult (String systemId) / / systemId:Must be a String that conforms to the URI syntax / / so the source Source And the result Result solves transformer.transform (new DOMSource (document), new StreamResult ("src/book.xml")). } / / extraction method (right-- > > refactor--- > > rctract method)-> refactoring-- extraction method private Document getDocument () throws ParserConfigurationException, SAXException, IOException {/ / 1. Get the factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); / / 2. Get the builder object DocumentBuilder builder = factory.newDocumentBuilder (); / / 3. Get the document object Document document = builder.parse ("src/book.xml") that represents the xml file; return document;}} Thank you for reading! This is the end of this article on "sample Analysis of JAXP in XML". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.