導航:首頁 > 編程語言 > xml添加節點java

xml添加節點java

發布時間:2022-12-18 04:59:41

A. java中的XML追加內容,追加節點,和節點的內容,還要常用的設計模式的代碼

/**
* 根據Xml文件生成Document對象
*
* @param file
* xml文件路徑
* @return Document對象
* @throws DocumentException
*/
public static Document getDocument(String path) throws DocumentException {
File file = new File(path);
SAXReader xmlReader = new SAXReader();
return xmlReader.read(file);
}

/**
* 根據輸入流生成Document對象
*
* @param is
* 輸入流
* @return Document對象
* @throws DocumentException
*/
public static Document getDocument(InputStream is) throws DocumentException {
SAXReader xmlReader = new SAXReader();
return xmlReader.read(is);
}

/**
* 根據Document得到根結點
*
* @param doc
* Document目錄
* @return 根結點
* @throws DocumentException
*/
public static Element getRoot(String path) throws DocumentException {
Document doc = getDocument(path);
return doc.getRootElement();
}

/**
* 取出當前結點下的所有子結點
*
* @param root
* 當前結點
* @return 一組Element
* @throws DocumentException
*/
@SuppressWarnings("unchecked")
public static List<Element> getElements(String path)
throws DocumentException {
Element root = getRoot(path);
return root.elements();
}

/**
* 根據元素名稱返回一組Element
*
* @param root
* 當前結點
* @param name
* 要返回的元素名稱
* @return 一組Element
* @throws DocumentException
*/
@SuppressWarnings("unchecked")
public static List<Element> getElementsByName(String path, String name)
throws DocumentException {
Element root = getRoot(path);
return root.elements(name);
}

/**
* 根據元素名稱返回一個元素(如果有多個元素的話,只返回第一個)
*
* @param root
* 當前結點
* @param name
* 要返回的元素名稱
* @return 一個Element元素
* @throws DocumentException
*/
public static Element getElementByName(String path, String name)
throws DocumentException {
Element root = getRoot(path);
return root.element(name);
}

/**
* 根據當前元素,返回該元素的所有屬性
*
* @param root
* 當前結點
* @return 當前結點的所有屬性
* @throws DocumentException
*/
@SuppressWarnings("unchecked")
public static List<Attribute> getAttributes(String path)
throws DocumentException {
Element root = getRoot(path);
return root.attributes();
}

/**
* 根據屬性名稱,返回當前元素的某個屬性
*
* @param root
* 當前結點
* @return 當前結點的一個屬性
* @throws DocumentException
*/
public static Attribute getAttributeByName(String path, String name)
throws DocumentException {
Element root = getRoot(path);
return root.attribute(name);
}
public static List<Element> getElementWithAttribute(String path,String attr,String value) throws DocumentException{
List<Element> elist = new ArrayList<Element>() ;
List<Element> list = getElements(path);
for(Element element:list){
if(element.attribute(attr).getText().equals(value)){
elist.add(element);
}
}
try {
elist.add(getElementSelf(path, attr, value));
} catch (Exception e) {
// TODO: handle exception
}
return elist;
}
public static Element getElementSelf(String path,String attr,String value) throws DocumentException{
Element element = null ;
List<Element> list = getElements(path);
for(Element e:list){
if(e.attribute(attr).getText().equals(value)){
element = e ;
}
}
return element;
}

B. Java xml 創建新節點後賦值

這是一個用JAVA W3C DOM 進行XML操作的例子,包含了查詢、增加、修改、刪除、保存的基本操作。較完整的描述了一個XML的整個操作流程。適合剛入門JAVA XML操作的朋友參考和學習。

假設有XML文件:test1.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>

下面是為Test.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;

public class Test {
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
Element theBook=null, theElem=null, root=null;
try {
factory.(true);

DocumentBuilder db=factory.newDocumentBuilder();
Document xmldoc=db.parse(new File("Test1.xml"));
root=xmldoc.getDocumentElement();

//--- 新建一本書開始 ----
theBook=xmldoc.createElement("book");
theElem=xmldoc.createElement("name");
theElem.setTextContent("新書");
theBook.appendChild(theElem);

theElem=xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);

theElem=xmldoc.createElement("memo");
theElem.setTextContent("新書的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- 新建一本書開始 ----");
output(xmldoc);
//--- 新建一本書完成 ----

//--- 下面對《哈里波特》做一些修改。 ----
//--- 查詢找《哈里波特》----
theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
System.out.println("--- 查詢找《哈里波特》 ----");
output(theBook);
//--- 此時修改這本書的價格 -----
theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當於xpath的".//price"。
System.out.println("--- 此時修改這本書的價格 ----");
output(theBook);
//--- 另外還想加一個屬性id,值為B01 ----
theBook.setAttribute("id", "B01");
System.out.println("--- 另外還想加一個屬性id,值為B01 ----");
output(theBook);
//--- 對《哈里波特》修改完成。 ----

//--- 要用id屬性刪除《三國演義》這本書 ----
theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
System.out.println("--- 要用id屬性刪除《三國演義》這本書 ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- 刪除後的XML ----");
output(xmldoc);

//--- 再將所有價格低於10的書刪除 ----
NodeList someBooks=selectNodes("/books/book[price<10]", root);
System.out.println("--- 再將所有價格低於10的書刪除 ---");
System.out.println("--- 符合條件的書有"+someBooks.getLength()+"本。 ---");
for(int i=0;i<someBooks.getLength();i++) {
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}
output(xmldoc);

saveXml("Test1_Edited.xml", xmldoc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void output(Node node) {//將node的XML字元串輸出到控制台
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "gb2312");
transformer.setOutputProperty("indent", "yes");

DOMSource source=new DOMSource();
source.setNode(node);
StreamResult result=new StreamResult();
result.setOutputStream(System.out);

transformer.transform(source, result);
} catch ( e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}

public static Node selectSingleNode(String express, Object source) {//查找節點,並返回第一個符合條件節點
Node result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return result;
}

public static NodeList selectNodes(String express, Object source) {//查找節點,返回符合條件的節點集。
NodeList result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return result;
}

public static void saveXml(String fileName, Document doc) {//將Document輸出到文件
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");

DOMSource source=new DOMSource();
source.setNode(doc);
StreamResult result=new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));

transformer.transform(source, result);
} catch ( e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

C. 通過java如何操作xml向其節點中添加內容比如<say>想添加的內容</say>

<say>我是個字元串可以隨便填</say>
你是要代碼嗎
InputStream is= this.getClass.getInputStream("my.xml");
在通過 is獲得內容我就說他是 String xml=is....
String str="想添加的內容";
String newxml=xml.replace("我是個字元串可以隨便填",str);

D. java 添加節點並保存成XML問題

在java編程中,用dom4j的api來處理xml,很簡單的,給段代碼,需要導入dom4j.jar

Documentdoc=DocumentHelper.createDocument();

//根節點

ElementrootEle=doc.addElement("root");

Elementele1=rootEle.addElement("ele1");

ele1.addText("節點1");

Elementele2=rootEle.addElement("ele2");

ele2.addText("節點2");

System.out.println(doc.asXML());

E. 在java中,使用JDOM怎麼給XML添加一個元素節點和一個屬性節點

Element e = new Element("root");//根節點
Element ele = new Element("Class");//Class節點
ele.setAttribute("name","二年1班");//為class節點增加屬性為name,值為二年一班的節點

F. java對xml文件添加節點

/*
這里使用了dom4j組件,你需要自己去下載dom4j。
其中a.xml是你的源文件。
這個程序沒有向磁碟中創建一個新文件,你可以自己修改代碼。
例如:
XMLWriter xmlWriter = new XMLWriter(new PrintWriter(System.out), format);
可以修改為
XMLWriter xmlWriter = new XMLWriter(new FileWriter("a.xml"), format);
這樣就可以修改源文件a.xml了。
*/

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.SAXReader;

import java.io.*;

public class Test {
public static void main(String[] args) {
SAXReader saxReader = new SAXReader();
try {
Document doc = saxReader.read(new File("a.xml"));
doc.getRootElement().addElement("PARAM")
.addElement("TASKLIST").addElement("TASK")
.addElement("DATA_TRAN_ID").addCDATA("14595");

OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
XMLWriter xmlWriter = new XMLWriter(new PrintWriter(System.out), format);
xmlWriter.write(doc);
xmlWriter.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}

G. java如何在為XML添加新節點

dom操作Java,需要下載dom4j.jar包。
具體操作請見:http://blog.csdn.net/cds27/archive/2008/03/02/2139110.aspx

H. java xml節點添加修改屬性

SAXReader reader = new SAXReader();
Document doc = reader.read(new FileInputStream("d.xml"));
Element root = doc.getRootElement();
List<Element> list = root.selectNodes("//here");
for (Element e : list) {
System.out.println(e);
e.addAttribute("color", "q");
}
// 保存
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(doc);
writer.close();

I. java用dom更新xml的問題,怎麼在子節點下添加節點

用dom找到子節點,用create方法創建節點,然後把它加到子節點上

J. JAVA設置XML根節點屬性

在menu節點的時候增加一個屬性,就成那個樣子了。
而<a>test</a>屬於menu結點的子節點。

在Element menu = dom.createElement("menu");
menu.setAttribute("id", "value");

閱讀全文

與xml添加節點java相關的資料

熱點內容
dvd光碟存儲漢子演算法 瀏覽:758
蘋果郵件無法連接伺服器地址 瀏覽:963
phpffmpeg轉碼 瀏覽:672
長沙好玩的解壓項目 瀏覽:145
專屬學情分析報告是什麼app 瀏覽:564
php工程部署 瀏覽:833
android全屏透明 瀏覽:737
阿里雲伺服器已開通怎麼辦 瀏覽:803
光遇為什麼登錄時伺服器已滿 瀏覽:302
PDF分析 瀏覽:486
h3c光纖全工半全工設置命令 瀏覽:143
公司法pdf下載 瀏覽:383
linuxmarkdown 瀏覽:350
華為手機怎麼多選文件夾 瀏覽:683
如何取消命令方塊指令 瀏覽:350
風翼app為什麼進不去了 瀏覽:779
im4java壓縮圖片 瀏覽:362
數據查詢網站源碼 瀏覽:151
伊克塞爾文檔怎麼進行加密 瀏覽:893
app轉賬是什麼 瀏覽:163