java对xml文件的读写_java 自己做的对XML文件的读写操作
XML文件實例:
WEB-INF/web.xml
type="javax.sql.DataSource" />
type="javax.sql.DataSource" />
Java類:
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.metadata.IIOMetadataNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.sun.org.apache.xerces.internal.dom.AttrNSImpl;
import com.sun.org.apache.xerces.internal.impl.xs.opti.DefaultNode;
public class T2 {
/**
* 將修改的內(nèi)容添加到xml文件中
*
* @param document
* @param filename
* @return
*/
public static boolean doc2XmlFile(Document document, String filename) {
boolean flag = true;
try {
/** 將document中的內(nèi)容寫入文件中 */
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
/** 編碼 */
//transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
DOMSource source = new DOMSource(document);
//判斷路徑開頭有沒有“/”如果有則去掉
filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);
StreamResult result = new StreamResult(new FileOutputStream(filename));
transformer.transform(source, result);
} catch (Exception ex) {
flag = false;
ex.printStackTrace();
}
return flag;
}
/**
* 讀取xml文件
*
* @param filename
* @return
*/
public static Document load(String filename) {
Document document = null;
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
//判斷路徑開頭有沒有“/”如果有則去掉
filename = "C".equals(filename.charAt(0)) ? filename : filename.substring(1);
document = builder.parse(new FileInputStream(filename));
document.normalize();
} catch (Exception ex) {
ex.printStackTrace();
logger.error("找不到文件!");
}
return document;
}
/**
* 演示修改文件的具體某個節(jié)點的值
*/
public static void xmlUpdateDemo() {
Document document = load("c://Message.xml");
Node root = document.getDocumentElement();
/** 如果root有子元素 */
if (root.hasChildNodes()) {
/** ftpnodes */
NodeList ftpnodes = root.getChildNodes();
/** 循環(huán)取得ftp所有節(jié)點 */
for (int i = 0; i < ftpnodes.getLength(); i++) {
NodeList ftplist = ftpnodes.item(i).getChildNodes();
for (int k = 0; k < ftplist.getLength(); k++) {
Node subnode = ftplist.item(k);
//修改節(jié)點的值
if (subnode.getNodeType() == Node.ELEMENT_NODE
&& subnode.getNodeName() == "status") {
subnode.getFirstChild().setNodeValue("1");
}
}
}
}
doc2XmlFile(document, "c://Message.xml");
}
/**
* 演示修改文件的具體某個節(jié)點的屬性
*/
public static void xmlUpdateDemoAttri() {
Document document = load("c://xx.xml");
Node root = document.getDocumentElement();
/** 如果root有子元素 */
if (root.hasChildNodes()) {
/** ftpnodes 根節(jié)點的子節(jié)點 */
NodeList ftpnodes = root.getChildNodes();
/** 循環(huán)取得第一層子節(jié)點所有節(jié)點 */
for (int i = 0; i < ftpnodes.getLength(); i++) {
Node subnode = ftpnodes.item(i);
//添加或修改某節(jié)點的屬性配置
if ("Resource".equals(subnode.getNodeName())) {
// 生成一個屬性對象
Attr attr = document.createAttribute("ss");
attr.setValue("ssss");
subnode.getAttributes().setNamedItem(attr);
}
}
}
// 將修改的內(nèi)容添加到xml文件中
doc2XmlFile(document, "c://xx.xml");
}
/**添加新的節(jié)點
* 根節(jié)點下沒有節(jié)點的話直接添加
* 根節(jié)點下沒有重名的直接添加
* 有重名的節(jié)點則更新節(jié)點屬性
* @param nodeName 添加、更新的節(jié)點名
* @param attr 屬性集合
*/
public static void xmlAddDemoAttri(String filePath,String nodeName,Map attr) {
Document document = load(filePath);
Node root = document.getDocumentElement();
//創(chuàng)建節(jié)點元素,并命名
Element element =document.createElement(nodeName);
//向節(jié)點中添加屬性
for (Object key : attr.keySet().toArray()) {
element.setAttribute(key.toString(), attr.get(key));
}
//找到根節(jié)點
NodeList nodeList = document.getElementsByTagName("Context");
//先判斷根節(jié)點下有沒有子節(jié)點,沒有的話直接添加
Node rootNode = nodeList.item(0);
if(!root.hasChildNodes()){
nodeList.item(0).appendChild(element);
}else{
//如果有重復的節(jié)點,flag=true;
boolean flag = false;
NodeList rootChs = rootNode.getChildNodes();
//循環(huán)根節(jié)點下的所有子節(jié)點
for (int i = 0; i < rootChs.getLength(); i++) {
Node node = rootChs.item(i);
//如果沒有重名,并且是最后一個節(jié)點的就添加
if(!nodeName.equals(node.getNodeName()) && !flag && (i+1) == rootChs.getLength()){
nodeList.item(0).appendChild(element);
}else if(nodeName.equals(node.getNodeName())){
//有重名的就看name屬性,name一樣就修改屬性
if(node.hasAttributes()){
//如果有屬性項,判斷name屬性值,如果name的值相同,則修改其他屬性
if(null != node.getAttributes().getNamedItem("name") && attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue())){
// 生成一個屬性對象
Attr chAttr = null;
//向節(jié)點中添加屬性
for (Object key : attr.keySet().toArray()) {
//不更新name屬性
if(!"name".equals(key.toString())){
chAttr = document.createAttribute(key.toString());
chAttr.setValue(attr.get(key));
}
}
node.getAttributes().setNamedItem(chAttr);
}else if(null != node.getAttributes().getNamedItem("name") && !attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue()) && !flag && (i+1) == rootChs.getLength()){
//如果name的值不相同,且都沒有相同的節(jié)點,添加新的節(jié)點
System.out.println(attr.get("name"));
System.out.println(node.getAttributes().getNamedItem("name").getNodeValue());
nodeList.item(0).appendChild(element);
}
}
}
}
}
// 將修改的內(nèi)容添加到xml文件中
doc2XmlFile(document, filePath);
}
public static void main(String args[]) throws Exception {
Map att = new HashMap();
att.put("as", "mmmmmmmmmmmmm");
att.put("name", "jdbc/sqlserver-database");
xmlAddDemoAttri("c://context.xml","Resource",att);
}
}
總結(jié)
以上是生活随笔為你收集整理的java对xml文件的读写_java 自己做的对XML文件的读写操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java jdk 1.8 配置_java
- 下一篇: java怎样开关语句随机数 不重复_怎样