java,c# 操作xml文件

来源:互联网 发布:linux命令语法格式 编辑:程序博客网 时间:2024/06/05 12:40

XML文件   poem.xml

<?xml version="1.0" encoding="UTF-8"?>
<poems>
  <poem id="1" title="观沧海" author="曹操">
    <content>树木丛生,百草丰茂。秋风萧瑟,洪波涌起。</content>
    <explain>树木</explain>
  </poem>
  <poem id="2" title="饮酒" author="陶渊明">
    <content>结庐在人境,而无车马喧。问君何能尔?心远地自偏。</content>
    <explain>结庐</explain>
  </poem>
</poems>


C#操作XML


引入命名空间

using System.IO;
using System.Xml;

static void Main(string[] args)
        {
            string idvalue = "1";
            string titlevalue = "观沧海";
            string authorvalue = "曹操";
            string contentvalue = "树木丛生,百草丰茂。秋风萧瑟,洪波涌起。";
            string explainvalue = "树木";
            //新建对象
            XmlDocument doc = new XmlDocument();
            //如果poem.xml文件不存在,则重新创建并写入xml节点和根节点
            if (!File.Exists("poem.xml"))
            {
                //XML版本和编码声明
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
                //添加根元素
                doc.AppendChild(doc.CreateElement("poems"));


                //获取根节点
                XmlNode rootpoems = doc.SelectSingleNode("/poems");
                //新建poem节点
                XmlNode newpoem = doc.CreateElement("poem");
                //新建id属性
                XmlAttribute tempatt = doc.CreateAttribute("id");
                tempatt.Value = idvalue;
                //添加属性
                newpoem.Attributes.Append(tempatt);
                tempatt = doc.CreateAttribute("title");
                tempatt.Value = titlevalue;
                newpoem.Attributes.Append(tempatt);
                tempatt = doc.CreateAttribute("author");
                tempatt.Value = authorvalue;
                newpoem.Attributes.Append(tempatt);
                XmlNode tempnode = doc.CreateElement("content");
                tempnode.InnerText = contentvalue;
                //添加节点
                newpoem.AppendChild(tempnode);
                tempnode = doc.CreateElement("explain");
                tempnode.InnerText = explainvalue;
                newpoem.AppendChild(tempnode);
                rootpoems.AppendChild(newpoem);


                //保存(若只访问,则不用保存)
                doc.Save("poem.xml");
            }
            //加载xml文件
            doc.Load("poem.xml");
            //获取根节点
            XmlNode poems = doc.SelectSingleNode("poems");
            //获取poem节点集合
            XmlNodeList poemss = poems.SelectNodes("poem");
            //根据属性查找节点,若有多个,则SelectSingleNode方法返回第一个
            XmlNode poemvalue1 = poems.SelectSingleNode("poem[@id='" + idvalue + "']");
            //根据多属性查找节点
            XmlNode poemvalue2 = poems.SelectSingleNode("poem[@id='" + idvalue + "' and @title='" + titlevalue + "']");
            //根据子节点内容查找节点
            XmlNode poemvalue3 = poems.SelectSingleNode("poem[explainvalue='" + explainvalue + "']");
            //根据节点内容查找节点
            XmlNode poemvalue4 = poems.SelectSingleNode("poem/content[text()='"+contentvalue+"']");
            //查找最后一个节点
            XmlNode poemvalue5 = poems.SelectSingleNode("poem[last()]");    


            //修改节点值
            poemvalue4.InnerText = explainvalue;
            //修改节点属性值
            poemvalue1.Attributes["title"].Value = "sun";


            //获取最后一个节点的id值
            try
            {
                if (poemss.Count > 0)
                    idvalue = (Int32.Parse(poemss[poemss.Count - 1].Attributes["id"].Value) + 1).ToString();
            }
            catch {  }
            //删除第一个poem节点
            poems.RemoveChild(poemss[0]);
            
            //保存(若只访问,则不用保存)
            doc.Save("poem.xml");
        }



java操作XML

需要先导入dom4j和jaxen架包

免费下载地址:http://download.csdn.net/detail/houcunyue/5388367

引入命名空间

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public static void main(String[] args) throws Exception {
String idvalue = "1";
        String titlevalue = "观沧海";
        String authorvalue = "曹操";
        String contentvalue = "树木丛生,百草丰茂。秋风萧瑟,洪波涌起。";
        String explainvalue = "树木";
        
        //声明文档对象
        Document doc=null;
        //如果poem.xml文件不存在,则重新创建并写入xml节点和根节点
        if (!new File("poem.xml").exists())
        {
        //创建xml
        doc=DocumentHelper.createDocument();
        //添加根元素
        Element poems=doc.addElement("poems");
        //新建poem节点,添加id,title,author属性。因为操作结果返回原节点,所以可连续添加。
        Element poem=poems.addElement("poem").addAttribute("id", idvalue).addAttribute("title", titlevalue).addAttribute("author", authorvalue);
        //添加子节点
            Element content=poem.addElement("content");
        //给节点赋值
            content.setText(contentvalue);
        Element explain=poem.addElement("explain");
        explain.setText(explainvalue);
       
            //保存xml文件
        OutputFormat format = OutputFormat.createPrettyPrint(); 
            //设置编码
        format.setEncoding("UTF-8"); 
        //写入
        XMLWriter writer=new XMLWriter(new FileWriter(new File("poem.xml")), format);
writer.write(doc);
writer.close();
        }
        //新建对象
        SAXReader reader=new SAXReader();
        //加载xml文件
        doc = reader.read(new File("poem.xml"));
        //获取根节点
        Element poems = (Element) doc.selectSingleNode("/poems");
        //获取poem节点集合
        List poemss = poems.selectNodes("poem");
        //根据属性查找节点,若有多个,则SelectSingleNode方法返回第一个
        Element poemvalue1 = (Element) poems.selectSingleNode("poem[@id='" + idvalue + "']");
        //根据多属性查找节点
        Element poemvalue2 = (Element) poems.selectSingleNode("poem[@id='" + idvalue + "' and @title='" + titlevalue + "']");
        //根据子节点内容查找节点
        Element poemvalue3 = (Element) poems.selectSingleNode("poem[explainvalue='" + explainvalue + "']");
        //根据节点内容查找节点
        Element poemvalue4 = (Element) poems.selectSingleNode("poem/content[text()='"+contentvalue+"']");
        //获取最后一个节点
        Element poemvalue5 = (Element) poems.selectSingleNode("poem[last()]");
        
        //修改节点值
        poemvalue4.setText(explainvalue);
        //修改节点属性值
        poemvalue1.setAttributeValue("author", "sun");


        //获取最后一个节点的id值
        if (poemss.size() > 0)
            idvalue = String.valueOf((Integer.parseInt(((Element)poemss.get(poemss.size() - 1)).attributeValue("id")) + 1));
        
        //删除最后一个poem节点
        poems.remove(poemvalue5);
        
        //保存(若只访问,则不用保存)
        //设置编码
    OutputFormat format = OutputFormat.createPrettyPrint(); 
        //设置编码
    format.setEncoding("UTF-8"); 
    //写入
    XMLWriter writer=new XMLWriter(new FileWriter(new File("poem.xml")), format);
writer.write(doc);
writer.close();
}

原创粉丝点击