<xml version="10" encoding="gbk">
<head></head>
<body></body>
可以在节点中加属性例如:
<body id = "" name = ""></body>
java代码解析一般用DOM4j分两种类型的解析方式:
1DOM: Document Object Model 文档对象模型
树形结构装载到内存中完成后才开始解析
缺点:如果文件比较大,内存有压力,时间会延迟
优点:可以对树形结构做任何 *** 作:加节点,删节点,遍历
2SAX: Simple API for XML
流(Stream)的特征,解析可以立即开始
不保存数据 对内存无压力不能修改节点
适合大文件的解析
下面附上代码:
public static List<String> parseCustomXML(String fileName) {
// 定义解析器
SAXReader saxReader = new SAXReader();
List<String> eleList = new ArrayList<String>();
// 开始解析,返回文档对象
/
<root>
<msg>
<element totalLenghtorder = "1" totalLenghtlenght = "8">totalLenght</element>
<element totalLenghtorder = "2" totalLenghtlenght = "8">bodyLenght</element>
<element jydmorder = "3" jydmlenght = "6">jydm</element>
<element msgTypeorder = "4" msgTypelenght = "2">msgType</element>
<element sendSignorder = "5" sendSignlenght = "1">sendSign</element>
<element msgCheckCodeorder = "6" msgCheckCodelenght = "32">msgCheckCode</element>
<element serviceNameorder = "7" serviceNamelenght = "8">serviceName</element>
<element msgAgreementorder = "8" msgAgreementlenght = "1">msgAgreement</element>
<element cprqorder = "9" cprqlenght = "8">cprq</element>
<element fkrzhorder = "10" fkrzhlenght = "20">fkrzh</element>
<element pjhmorder = "11" pjhmlenght = "8">pjhm</element>
<element jeorder = "12" jelenght = "20">je</element>
<element zfmmorder = "13" zfmmlenght = "20">zfmm</element>
<element jghorder = "14" jghlenght = "20">jgh</element>
<element yhdmorder = "15" yhdmlenght = "20">yhdm</element>
</msg>
</root>
/
try {
Document doc = saxReaderread(new File(fileName));
Element root = docgetRootElement();// 获取根节点
Element msg = rootelement("msg");
Iterator itEle = msgelementIterator("element");// 遍历msg节点下的所有element节点
while (itElehasNext()) {
Element element = (Element) itElenext();
String value = elementgetText();
//测试
Systemoutprintln(value);
eleListadd(value);
Iterator itAttr = elementattributeIterator();// 遍历每一个element节点的所有属性
while (itAttrhasNext()) {
Attribute attr = (Attribute) itAttrnext();
//String keyAttr = attrgetName();
String valueAttr = attrgetValue();
//测试
Systemoutprintln(valueAttr);
eleListadd(valueAttr);
}
}
} catch (DocumentException e) {
eprintStackTrace();
}
return eleList;
}
有不明白的 在帮你分析第一种方法:用了转义字符把>和=CURRENT_DATE第二种方法:因为这个是xml格式的,所以不允许出现类似“>”这样的字符,但是都可以使用符号进行说明,将此类符号不进行解析你的可以写成这个:mapper文件示例代码[html]viewplaincopyimport javaioFile;
import javaioFileNotFoundException;
import javaioFileOutputStream;
import javaioIOException;
import orgw3cdom;
import orgxmlsaxSAXException;
import javaxxmlparsers;
import javaxxmltransform;
import javaxxmltransformdomDOMSource;
import javaxxmltransformstream;
import javaxxmlxpath;
public class Test {
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactorynewInstance();
Element theBook=null, theElem=null, root=null;
try {
factorysetIgnoringElementContentWhitespace(true);
DocumentBuilder db=factorynewDocumentBuilder();
Document xmldoc=dbparse(new File("Test1xml"));
root=xmldocgetDocumentElement();
theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
Systemoutprintln("--- 查询找《哈里波特》 ----");
Element nameNode=(Element)theBookgetElementsByTagName("price")item(0);
String name=nameNodegetFirstChild()getNodeValue();
Systemoutprintln(name);
output(theBook);
Systemoutprintln("=============selectSingleNode(books/book[name='哈里波特'], root)==================");
//--- 新建一本书开始 ----
theBook=xmldoccreateElement("book");
theElem=xmldoccreateElement("name");
theElemsetTextContent("新书");
theBookappendChild(theElem);
theElem=xmldoccreateElement("price");
theElemsetTextContent("20");
theBookappendChild(theElem);
theElem=xmldoccreateElement("memo");
theElemsetTextContent("新书的更好看。");
theBookappendChild(theElem);
rootappendChild(theBook);
Systemoutprintln("--- 新建一本书开始 ----");
output(xmldoc);
Systemoutprintln("==============================");
//--- 新建一本书完成 ----
//--- 下面对《哈里波特》做一些修改。 ----
//--- 查询找《哈里波特》----
//--- 此时修改这本书的价格 -----
theBookgetElementsByTagName("price")item(0)setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相当于xpath的"//price"。
Systemoutprintln("--- 此时修改这本书的价格 ----");
output(theBook);
//--- 另外还想加一个属性id,值为B01 ----
theBooksetAttribute("id", "B01");
Systemoutprintln("--- 另外还想加一个属性id,值为B01 ----");
output(theBook);
//--- 对《哈里波特》修改完成。 ----
//--- 要用id属性删除《三国演义》这本书 ----
theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
Systemoutprintln("--- 要用id属性删除《三国演义》这本书 ----");
output(theBook);
theBookgetParentNode()removeChild(theBook);
Systemoutprintln("--- 删除后的XML ----");
output(xmldoc);
//--- 再将所有价格低于10的书删除 ----
NodeList someBooks=selectNodes("/books/book[price<10]", root);
Systemoutprintln("--- 再将所有价格低于10的书删除 ---");
Systemoutprintln("--- 符合条件的书有 "+someBooksgetLength()+"本。 ---");
for(int i=0;i<someBooksgetLength();i++) {
someBooksitem(i)getParentNode()removeChild(someBooksitem(i));
}
output(xmldoc);
saveXml("Test1_Editedxml", xmldoc);
} catch (ParserConfigurationException e) {
eprintStackTrace();
} catch (SAXException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
}
}
public static void output(Node node) {//将node的XML字符串输出到控制台
TransformerFactory transFactory=TransformerFactorynewInstance();
try {
Transformer transformer = transFactorynewTransformer();
transformersetOutputProperty("encoding", "gb2312");
transformersetOutputProperty("indent", "yes");
DOMSource source=new DOMSource();
sourcesetNode(node);
StreamResult result=new StreamResult();
resultsetOutputStream(Systemout);
transformertransform(source, result);
} catch (TransformerConfigurationException e) {
eprintStackTrace();
} catch (TransformerException e) {
eprintStackTrace();
}
}
public static Node selectSingleNode(String express, Object source) {//查找节点,并返回第一个符合条件节点
Node result=null;
XPathFactory xpathFactory=XPathFactorynewInstance();
XPath xpath=xpathFactorynewXPath();
try {
result=(Node) xpathevaluate(express, source, XPathConstantsNODE);
} catch (XPathExpressionException e) {
eprintStackTrace();
}
return result;
}
public static NodeList selectNodes(String express, Object source) {//查找节点,返回符合条件的节点集。
NodeList result=null;
XPathFactory xpathFactory=XPathFactorynewInstance();
XPath xpath=xpathFactorynewXPath();
try {
result=(NodeList) xpathevaluate(express, source, XPathConstantsNODESET);
} catch (XPathExpressionException e) {
eprintStackTrace();
}
return result;
}
public static void saveXml(String fileName, Document doc) {//将Document输出到文件
TransformerFactory transFactory=TransformerFactorynewInstance();
try {
Transformer transformer = transFactorynewTransformer();
transformersetOutputProperty("indent", "yes");
DOMSource source=new DOMSource();
sourcesetNode(doc);
StreamResult result=new StreamResult();
resultsetOutputStream(new FileOutputStream(fileName));
transformertransform(source, result);
} catch (TransformerConfigurationException e) {
eprintStackTrace();
} catch (TransformerException e) {
eprintStackTrace();
} catch (FileNotFoundException e) {
eprintStackTrace();
}
}
}
XML:
<xml version="10" encoding="GBK">
<books>
<book>
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="B02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="B03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="B04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)