Jdom, Dom4j, W3c, String mutual conversion Daquan and take Xml Attribute values, set Xml Attribute values, delete Xm attribute values, jdom4j

Source: Internet
Author: User
Tags xml attribute

Jdom, Dom4j, W3c, String mutual conversion Daquan and take Xml Attribute values, set Xml Attribute values, delete Xm attribute values, jdom4j

Conversion between Jdom, Dom4j, W3c, and String, obtaining Xml Attribute values, setting Xml Attribute values, and deleting Xm attribute values

Source code:


Original article: mutual conversion between Jdom, Dom4j, W3c, and String, retrieving Xml Attribute values, setting Xml Attribute values, and deleting Xm attribute values

Source code: http://www.zuidaima.com/share/1550463324146688.htm


Package com. zuidaima. xml; import java. io. charArrayReader; import java. io. IOException; import java. io. stringReader; import java. io. stringWriter; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import org. apache. xerces. dom. entimpl; import org. apache. xerces. parsers. DOMParser; import org. apache. xml. serialize. outputFormat; import org. apache. xml. serialize. XMLSerializ Er; import org. apache. xpath. XPathAPI; import org. jdom. input. DOMBuilder; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList; import org. xml. sax. inputSource; import org. xml. sax. SAXException;/*** convert the document Object to string data * @ author www.zuidaima.com * @ param dom * @ return */public class XmlChange {/*** to convert the document object, convert to string data * @ param dom * @ return */public Static String dom2String (Document dom) // converts a document Object to String data. {String aa = new String (); try {StringWriter ss = new StringWriter (); OutputFormat format = new OutputFormat (dom); // Serialize DOMformat. setEncoding (& quot; GB2312 & quot;); XMLSerializer serial = new XMLSerializer (ss, format); serial. asDOMSerializer (); // As a DOM Serializerserial. serialize (dom. getDocumentElement (); aa = ss. toString (); ss. flush (); ss. close ();} catch (Exception e) {// return false;} return A;}/*** convert the String to document * @ author www.zuidaima.com * @ param XMLData * @ return */public static Document string2Dom (String XMLData) // parse the String xml data, generate document {// System. out. println (& quot; xml: & quot; + XMLData); Document dom = new jsonentimpl (); try {InputSource source = new InputSource (new CharArrayReader (XMLData. toCharArray (); System. out. println (& quot; ----- 888888 ==& quot; + source); DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory. newInstance (); DocumentBuilder docBuilder = docBuilderFactory. newDocumentBuilder (); dom = docBuilder. parse (source); System. out. println (& quot; ----- 888888 ==& quot; + dom) ;}catch (Exception e) {dom = null ;}finally {return dom ;}} /*** parse the string xml data, generate the document, and filter the spaces in the xml. * @ author www.zuidaima.com * @ param data * @ param isSpace * @ return * @ throws IOException * @ th Rows SAXException */public static Document string2Dom (String data, boolean isSpace) throws IOException, SAXException // parse the String xml data, generate a document, and filter spaces in the xml {if (isSpace) {DOMParser parser = new DOMParser (); StringReader sr = new StringReader (data); InputSource is = new InputSource (sr); parser. parse (is); sr. close (); return parser. getDocument () ;}else {return null ;}/ *** implements dom4j to org. w3c. dom. document conversion ** @ p Aram doc * @ return * @ throws Exception */public static org. w3c. dom. document dom4j2W3c (Document doc) throws Exception {if (doc = null) {return (null);} java. io. stringReader reader = new java. io. stringReader (doc. toString (); org. xml. sax. inputSource source = new org. xml. sax. inputSource (reader); javax. xml. parsers. documentBuilderFactory documentBuilderFactory = javax. xml. parsers. documentBuilderFactory. ne WInstance (); javax. xml. parsers. documentBuilder documentBuilder = documentBuilderFactory. newDocumentBuilder (); return (documentBuilder. parse (source);}/***** implement org. w3c. dom. conversion from Document to dom4j ** @ param doc * @ return * @ throws Exception */public static org. dom4j. document parse (org. w3c. dom. document doc) throws Exception {if (doc = null) {return (null);} org. dom4j. io. DOMReader xmlReader = new org. dom4j. Io. DOMReader (); return (xmlReader. read (doc);}/***** implement org. w3c. dom. conversion from Document to jdom ** @ param doc * @ return * @ throws Exception */public static org. jdom. document convertToJDOM (org. w3c. dom. document doc) throws Exception {if (doc = null) {return (null);} DOMBuilder builder = new DOMBuilder (); org. jdom. document jdomDoc = builder. build (doc); return jdomDoc;}/*** according to tagName, attributeName gets the corresponding Node from xml The property value may have multiple nodes defined by tagnames. Take the first ** @ param dom * @ param tagName * @ attributeName * @ return Attribute; */public static String getAttributeValueFromDom (Document dom, String tagName, String attributeName) {String result = & quot; if (dom! = Null & amp; tagName! = Null & amp ;! TagName. trim (). equals (& quot;) & amp; attributeName! = Null & amp ;! AttributeName. trim (). equals (& quot;) {NodeList nodeList = null; Node node = null; nodeList = dom. getElementsByTagName (tagName. trim (); if (nodeList! = Null & amp; nodeList. getLength () & gt; 0) {/*** there may be multiple nodes defined by tagnames in xml, and the first Node is */node = nodeList. item (0); if (node! = Null) {result = (Element) node). getAttribute (attributeName); result = null? & Quot;: result. trim () ;}} return result ;} /*** set the xml node property value ** @ param dom * @ param tagName * @ param attributeName * @ param value * @ return */public static boolean setAttributeValueFromDom (Document dom, string tagName, String attributeName, String value) {boolean result = false; if (dom! = Null & amp; tagName! = Null & amp ;! TagName. trim (). equals (& quot;) & amp; attributeName! = Null & amp ;! AttributeName. trim (). equals (& quot;) {NodeList nodeList = null; Node node = null; nodeList = dom. getElementsByTagName (tagName. trim (); if (nodeList! = Null & amp; nodeList. getLength () & gt; 0) {/*** there may be multiple nodes defined by tagnames in xml, and the first Node is */node = nodeList. item (0); if (node! = Null) {(Element) node ). setAttribute (attributeName, value); result = true ;}} return result ;} /*** get the corresponding Node value from xml based on the tagName ** @ param dom * @ param tagName * @ return */public static String getNodeValueFromDom (Document dom, String tagName) {String result = & quot; try {if (dom! = Null & amp; tagName! = Null & amp ;! TagName. trim (). equals (& quot;) {NodeList nodeList = null; Node node = null; nodeList = XPathAPI. selectNodeList (dom, tagName. trim (); // dom. getElementsByTagName (tagName. trim (); if (nodeList! = Null & amp; nodeList. getLength () & gt; 0) {/*** there may be multiple nodes defined by tagnames in xml, and the first Node is */node = nodeList. item (0); if (node! = Null) {node = node. getFirstChild (); if (node! = Null) result = node. getNodeValue (); result = null? & Quot;: result. trim () ;}}} catch (Exception e) {System. out. println (& quot; getNodeValueFromDom error = & quot; + e. toString (); e. printStackTrace ();} return result;} public static String getTagValueByTagName (Document dom, String tagName) {String result = & quot; try {if (dom! = Null & amp; tagName! = Null & amp ;! TagName. trim (). equals (& quot;) {NodeList nodeList = null; Node node = null; if (dom. getElementsByTagName (tagName. trim ())! = Null) {nodeList = dom. getElementsByTagName (tagName. trim (); if (nodeList. item (0 )! = Null) {node = nodeList. item (0); if (node. getChildNodes (). item (0). getNodeValue ()! = Null) {result = (node. getChildNodes ()). item (0 ). getNodeValue (). trim () ;}}}} catch (Exception e) {System. out. println (& quot; getNodeValueFromDom error = & quot; + e. toString (); e. printStackTrace ();} return result ;}}

 


Java uses dom4j to read xml (element attributes of the xml file are not considered for the moment), store the elements in the xml file in the form of a tree, and traverse the nodes in the middle order.

Package xml;

Import java. io. File;
Import java. util. Iterator;
Import java. util. List;

Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;

Import org. dom4j. Document;
Import org. dom4j. Element;
Import org. dom4j. io. DOMReader;

Public class XmlTest {

/**
* @ Param args
* @ Throws Exception
*/
Public static void main (String [] args) throws Exception {

DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance ();
DocumentBuilder db = dbf. newDocumentBuilder ();
File file = new File ("d:/test. xml ");
Org. w3c. dom. Document domDocument = db. parse (file );
DOMReader reader = new DOMReader ();
Document document = reader. read (domDocument );
Element root = document. getRootElement ();
List skills = root. elements ();
For (Iterator <?> It = skills. iterator (); it. hasNext ();){
Element e = (Element) it. next ();
System. out. println ("" + e. getName ());
List childrenList = e. elements ();
For (Iterator <?> Childit = childrenList. iterator (); childit. hasNext ();){
Element e2 = (Element) childit. next ();
System. out. println ("" + e2.getName () + "=" + e2.getText ());
}
}

}

}

* ***** Note that the node cannot be a pure number... the remaining full text>
 
Java processes string strings in a format like xml and obtains the content directly.

You can easily use the DOM, JDOM, or DOM4J parser. Go to the next JAR package on the Internet, and there will be APIs in it. If you have any questions, just ask me again. Hope to help you

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.