import 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>
你说的是获取指定id下面的节点的属性值吧!
程序如下,其中equal(“”)双引号中的值为节点的属性值
属性值获取如下:
package saxbuilderibmxmlproperty;
import javaioFile;
import javaioIOException;
import javautilIterator;
import orgdom4jAttribute;
import orgdom4jDocument;
import orgdom4jDocumentException;
import orgdom4jElement;
import orgdom4jioSAXReader;
import orgjdomJDOMException;
import orgjdominputSAXBuilder;
public class XmlProperty {
public Element element;
String path = "D:\\xml\\axml";
public void getElementProperty() {
File file = new File(path);
try {
SAXReader reader = new SAXReader();
Document dc = readerread(file);
Element e = dcgetRootElement();
// 节点值
Element child = (Element) egetQName("COMMAND");
Systemoutprintln(childtoString());
// 一级节点
for (Iterator iterator = eelementIterator(); iteratorhasNext();) {
Element el = (Element) iteratornext();
// 一级节点的属性信息
for (Iterator iterator2 = elattributeIterator(); iterator2
hasNext();) {
Attribute attribute = (Attribute) iterator2next();
if(attributegetName()equals("bodyCategory")){
Systemoutprintln("attributegetName()一级节点的属性信息+"+attributegetName()+attributegetValue());
}else{
Systemoutprintln("attributegetName()一级节点的属性信息+"+attributegetName()+attributegetValue());
}
// 二级节点
for (Iterator iterator3 = elelementIterator(); iterator3
hasNext();) {
Element ele = (Element) iterator3next();
// 二级节点的属性信息
for (Iterator iterator4 = eleattributeIterator(); iterator4
hasNext();) {
Attribute attribute1 = (Attribute) iterator4next();
if(attribute1getName()equals("cmdType")){
Systemoutprintln("attribute1getName()二级节点的属性信息+"+attribute1getName()+"+"+attribute1getValue());
}else{
Systemoutprintln("attribute1getName()二级节点的属性信息+"+attribute1getName()+"+"+attribute1getValue());
}
}
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
}
下面是一个java Servlet示例,用于接收POST提交过来的XML数据(仅供参考 ):
Java Servlet代码片段:
import javaio;
// Servlet doPost相关代码略去
BufferedReader in = requestgetReader();
String line;
String realPath = requestgetServletContext()getRealPath("/saved-datatxt");
File f = new File(realPath);
FileWriter fw = new FileWriter(realPath);
BufferedWriter bw = new BufferedWriter(fw);
try {
while ((line = inreadLine()) != null) {
outprintln(line);
bwwrite(line);
bwnewLine();
}
bwclose();
fwclose();
outprint("saved data ok!");
} catch (Exception e) {
eprintStackTrace();
outprintln("Mission Completed");
}
以上就是关于JAVA 生成xml格式,具体格式如下,请问JAVA方法怎么写全部的内容,包括:JAVA 生成xml格式,具体格式如下,请问JAVA方法怎么写、java语句如何获取XML文件的节点值、java 怎么接收第三方传过来的xml等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)