XML帮助类

1:带有一个路径的参数构造方法

 

using System.Xml;
using System.Data;
 
namespace DotNet.Utilities
{
    /// <summary>
    /// Xml的操作公共类
    /// </summary>    
    public class XmlHelper
    {
        #region 字段定义
        /// <summary>
        /// XML文件的物理路径
        /// </summary>
        private string _filePath = string.Empty;
        /// <summary>
        /// Xml文档
        /// </summary>
        private XmlDocument _xml;
        /// <summary>
        /// XML的根节点
        /// </summary>
        private XmlElement _element;
        #endregion
 
        #region 构造方法
        /// <summary>
        /// 实例化XmlHelper对象
        /// </summary>
        /// <param name="xmlFilePath">Xml文件的相对路径</param>
        public XmlHelper(string xmlFilePath)
        {
            //获取XML文件的绝对路径
            _filePath = SysHelper.GetPath(xmlFilePath);
        }
        #endregion
 
        #region 创建XML的根节点
        /// <summary>
        /// 创建XML的根节点
        /// </summary>
        private void CreateXMLElement()
        {
 
            //创建一个XML对象
            _xml = new XmlDocument();
 
            if (DirFile.IsExistFile(_filePath))
            {
                //加载XML文件
                _xml.Load(this._filePath);
            }
 
            //为XML的根节点赋值
            _element = _xml.DocumentElement;
        }
        #endregion
 
        #region 获取指定XPath表达式的节点对象
        /// <summary>
        /// 获取指定XPath表达式的节点对象
        /// </summary>        
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        public XmlNode GetNode(string xPath)
        {
            //创建XML的根节点
            CreateXMLElement();
 
            //返回XPath节点
            return _element.SelectSingleNode(xPath);
        }
        #endregion
 
        #region 获取指定XPath表达式节点的值
        /// <summary>
        /// 获取指定XPath表达式节点的值
        /// </summary>
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        public string GetValue(string xPath)
        {
            //创建XML的根节点
            CreateXMLElement();
 
            //返回XPath节点的值
            return _element.SelectSingleNode(xPath).InnerText;
        }
        #endregion
 
        #region 获取指定XPath表达式节点的属性值
        /// <summary>
        /// 获取指定XPath表达式节点的属性值
        /// </summary>
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        /// <param name="attributeName">属性名</param>
        public string GetAttributeValue(string xPath, string attributeName)
        {
            //创建XML的根节点
            CreateXMLElement();
 
            //返回XPath节点的属性值
            return _element.SelectSingleNode(xPath).Attributes[attributeName].Value;
        }
        #endregion
 
        #region 新增节点
        /// <summary>
        /// 1. 功能:新增节点。
        /// 2. 使用条件:将任意节点插入到当前Xml文件中。
        /// </summary>        
        /// <param name="xmlNode">要插入的Xml节点</param>
        public void AppendNode(XmlNode xmlNode)
        {
            //创建XML的根节点
            CreateXMLElement();
 
            //导入节点
            XmlNode node = _xml.ImportNode(xmlNode, true);
 
            //将节点插入到根节点下
            _element.AppendChild(node);
        }
 
        /// <summary>
        /// 1. 功能:新增节点。
        /// 2. 使用条件:将DataSet中的第一条记录插入Xml文件中。
        /// </summary>        
        /// <param name="ds">DataSet的实例,该DataSet中应该只有一条记录</param>
        public void AppendNode(DataSet ds)
        {
            //创建XmlDataDocument对象
            XmlDataDocument xmlDataDocument = new XmlDataDocument(ds);
 
            //导入节点
            XmlNode node = xmlDataDocument.DocumentElement.FirstChild;
 
            //将节点插入到根节点下
            AppendNode(node);
        }
        #endregion
 
        #region 删除节点
        /// <summary>
        /// 删除指定XPath表达式的节点
        /// </summary>        
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        public void RemoveNode(string xPath)
        {
            //创建XML的根节点
            CreateXMLElement();
 
            //获取要删除的节点
            XmlNode node = _xml.SelectSingleNode(xPath);
 
            //删除节点
            _element.RemoveChild(node);
        }
        #endregion //删除节点
 
        #region 保存XML文件
        /// <summary>
        /// 保存XML文件
        /// </summary>        
        public void Save()
        {
            //创建XML的根节点
            CreateXMLElement();
 
            //保存XML文件
            _xml.Save(this._filePath);
        }
        #endregion //保存XML文件
 
        #region 静态方法
 
        #region 创建根节点对象
        /// <summary>
        /// 创建根节点对象
        /// </summary>
        /// <param name="xmlFilePath">Xml文件的相对路径</param>        
        private static XmlElement CreateRootElement(string xmlFilePath)
        {
            //定义变量,表示XML文件的绝对路径
            string filePath = "";
 
            //获取XML文件的绝对路径
            filePath = SysHelper.GetPath(xmlFilePath);
 
            //创建XmlDocument对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文件
            xmlDocument.Load(filePath);
 
            //返回根节点
            return xmlDocument.DocumentElement;
        }
        #endregion
 
        #region 获取指定XPath表达式节点的值
        /// <summary>
        /// 获取指定XPath表达式节点的值
        /// </summary>
        /// <param name="xmlFilePath">Xml文件的相对路径</param>
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        public static string GetValue(string xmlFilePath, string xPath)
        {
            //创建根对象
            XmlElement rootElement = CreateRootElement(xmlFilePath);
 
            //返回XPath节点的值
            return rootElement.SelectSingleNode(xPath).InnerText;
        }
        #endregion
 
        #region 获取指定XPath表达式节点的属性值
        /// <summary>
        /// 获取指定XPath表达式节点的属性值
        /// </summary>
        /// <param name="xmlFilePath">Xml文件的相对路径</param>
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        /// <param name="attributeName">属性名</param>
        public static string GetAttributeValue(string xmlFilePath, string xPath, string attributeName)
        {
            //创建根对象
            XmlElement rootElement = CreateRootElement(xmlFilePath);
 
            //返回XPath节点的属性值
            return rootElement.SelectSingleNode(xPath).Attributes[attributeName].Value;
        }
        #endregion
 
        #endregion
 
        public static void SetValue(string xmlFilePath, string xPath, string newtext)
        {
            //string path = SysHelper.GetPath(xmlFilePath);
            //var queryXML = from xmlLog in xelem.Descendants("msg_log")
            //               //所有名字为Bin的记录
            //               where xmlLog.Element("user").Value == "Bin"
            //               select xmlLog;
 
            //foreach (XElement el in queryXML)
            //{
            //    el.Element("user").Value = "LiuBin";//开始修改
            //}
            //xelem.Save(path);
        }
    }
}

2:创建XML的根节点方法

XmlDocument doc = new XmlDocument(); //创建XmlDocument对象
doc.Load(Server.MapPath("newXml.xml")); //载入文件

XmlNode node = doc.DocumentElement;

XmlNode firstnode = node.FirstChild; //获取根节点 

3:新增节点方法

 public void Create(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             
 6             var root = xmlDoc.DocumentElement;//取到根结点
 7             XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
 8             newNode.InnerText = "WPF";
 9 
10             //添加为根元素的第一层子结点
11             root.AppendChild(newNode);
12             xmlDoc.Save(xmlPath);
13         }
开篇有写操作xml节点属性主要用XmlElement对象所以取到结点后要转类型 
 1         //属性
 2         public void CreateAttribute(string xmlPath)
 3         {
 4             XmlDocument xmlDoc = new XmlDocument();
 5             xmlDoc.Load(xmlPath);
 6             var root = xmlDoc.DocumentElement;//取到根结点
 7             XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
 8             node.SetAttribute("Name", "WPF");
 9             xmlDoc.Save(xmlPath);
10 
11         }

4:删除节点方法     

 public void Delete(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             var root = xmlDoc.DocumentElement;//取到根结点
 6 
 7             var element = xmlDoc.SelectSingleNode("BookStore/NewBook");
 8             root.RemoveChild(element);
 9             xmlDoc.Save(xmlPath);
10         }
删除属性
 1         public void DeleteAttribute(string xmlPath)
 2         {
 3             XmlDocument xmlDoc = new XmlDocument();
 4             xmlDoc.Load(xmlPath);
 5             XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
 6             //移除指定属性
 7             node.RemoveAttribute("Name");
 8             //移除当前节点所有属性,不包括默认属性
 9             //node.RemoveAllAttributes();
10             xmlDoc.Save(xmlPath);
11         }

5:保存XML文件方法

public void WriteXml()
    {
        //创建一个数据集,将其写入xml文件
        string optime = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
        System.Data.DataSet ds = new System.Data.DataSet("MESSAGE");
        System.Data.DataTable table = new System.Data.DataTable("FeedBack");
        ds.Tables.Add(table);
        table.Columns.Add("ID", typeof(string));
        table.Columns.Add("email", typeof(string));
        table.Columns.Add("telephone", typeof(string));
        table.Columns.Add("problem", typeof(string));

        System.Data.DataRow row = table.NewRow();
        row[0] = DateTime.Now.ToString("yyyyMMddHHmmss");
        row[1] = this.txtEmail.Text;
        row[2] = this.txtMobile.Text;
        row[3] = this.txtBody.Text;
        ds.Tables["FeedBack"].Rows.Add(row);

        string path = Server.MapPath("~/feedback/" + optime);
        ds.WriteXml(path);
    }

6:创建根节点对象方法

static void Main(string[] args)
        {
            XmlDocument myXML = new XmlDocument();
            XmlDeclaration myDeclaration = myXML.CreateXmlDeclaration("1.0", "GBK", null);
            myXML.AppendChild(myDeclaration);
            XmlNode goods = myXML.CreateNode(XmlNodeType.Element,"goods",null);
            myXML.AppendChild(goods);
            XmlNode price = myXML.CreateNode(XmlNodeType.Element, "price", null);
            price.InnerText = "$3/kg";
            goods.AppendChild(price);
            XmlNode sub = myXML.CreateNode(XmlNodeType.Element, "sub", null);
            goods.AppendChild(sub);

            XmlNode weight = myXML.CreateNode(XmlNodeType.Element, "weight", null);
            weight.InnerText = "88kg";
            sub.AppendChild(weight);

            sub.AppendChild(price);

            Console.WriteLine(myXML.InnerXml);
            Console.ReadKey();
        }

  7:获取指定XPath表达式节点的值方法

<Properties>
<Property Descriptor="100">1377349460.298</Property>
<Property Descriptor="101">1</Property>
<Property Descriptor="24000">fail</Property>
</Properties>
<Properties>
<Property Descriptor="100">1377349462.298</Property>
<Property Descriptor="101">1</Property>
<Property Descriptor="24000">pass</Property>
</Properties>

比如上面的xml  我要获取 Property节点值为fail的节点信息。  


 XmlNode xmlnoderesult = doc.SelectSingleNode("//Property[text()='fail']");

8:获取指定XPath表达式节点的属性值方法  

myPage = '''<html>
        <title>TITLE</title>
        <body>
        <h1>我的博客</h1>
        <div>我的文章</div>
        <div id="photos">
         <img src="pic1.jpeg"/><span id="pic1">PIC1 is beautiful!</span>
         <img src="pic2.jpeg"/><span id="pic2">PIC2 is beautiful!</span>
         <p><a href="http://www.example.com/more_pic.html">更多美图</a></p>
         <a href="http://www.baidu.com">去往百度</a>
         <a href="http://www.163.com">去往网易</a>
         <a href="http://www.sohu.com">去往搜狐</a>
        </div>
        <p class="myclassname">Hello,\nworld!<br/>-- by Adam</p>
        <div class="foot">放在尾部的其他一些说明</div>
        </body>
        </html>'''
        
html = etree.fromstring(myPage)

# 一、定位
divs1 = html.xpath('//div')
divs2 = html.xpath('//div[@id]')
divs3 = html.xpath('//div[@class="foot"]')
divs4 = html.xpath('//div[@*]')
divs5 = html.xpath('//div[1]')
divs6 = html.xpath('//div[last()-1]')
divs7 = html.xpath('//div[position()<3]')
divs8 = html.xpath('//div|//h1')
divs9 = html.xpath('//div[not(@*)]')

# 二、取文本 text() 区别 html.xpath('string()')
text1 = html.xpath('//div/text()')
text2 = html.xpath('//div[@id]/text()')
text3 = html.xpath('//div[@class="foot"]/text()')
text4 = html.xpath('//div[@*]/text()')
text5 = html.xpath('//div[1]/text()')
text6 = html.xpath('//div[last()-1]/text()')
text7 = html.xpath('//div[position()<3]/text()')
text8 = html.xpath('//div/text()|//h1/text()')


# 三、取属性 @
value1 = html.xpath('//a/@href')
value2 = html.xpath('//img/@src')
value3 = html.xpath('//div[2]/span/@id')

 9:获取指定XPath表达式的节点对象方法

目标: 学习xpath表达式找节点对象

相关的api类与方法:

JXDocument
    new JxDocument(document )  得到jxDocumnet
    selN("路径")    找多个节点
    selNone("路径")  找一个节点

JxNode 对象
    Element getElement()
    List<JXNode> sel(String xpath)

*/

import cn.wanghaomiao.xpath.model.JXDocument;
import cn.wanghaomiao.xpath.model.JXNode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;

import java.io.File;
import java.util.List;

public class Demo1 {

   /* 1)绝对路径表达式: 绝对路径找节点一定是以“/”开头,“/”代表了当前的html或者xml文件根节点。
   注意: 绝对路径找节点绝对不能跳级去寻找节点。
   * */
   @Test
    public void test01() throws  Exception{
        //1 得到JXDocument
        Document document = Jsoup.parse(new File(Demo1.class.getResource("/index.html").getPath()),"utf-8");
        JXDocument jxDocument  = new JXDocument(document);
        //需求: /body/div/ul/li
         List<JXNode> list = jxDocument.selN("/body/div/ul/li");
        for (JXNode jxNode : list) {
            System.out.println(jxNode);
        }
    }




    /* 2. 相对路径找节点: 使用相对路径找节点的时候一定要清楚当前节点是谁。 所谓的相对路就是要寻找的节点相对于当前节点。

    当前节点就是执行了sel方法的对象。

  * */
    @Test
    public void test02() throws  Exception {
        //1 得到JXDocument
        Document document = Jsoup.parse(new File(Demo1.class.getResource("/index.html").getPath()), "utf-8");
        JXDocument jxDocument = new JXDocument(document);

        //需求:先采用绝对路径获取body节点,再采用相对路径获取下一级div节点列表并打印信息
        JXNode headerNode =  jxDocument.selNOne("/body/header");

        List<JXNode> list =   headerNode.sel("div/img") ; //谁执行了sel方法,那么谁就是当前节点。
        for (JXNode jxNode : list) {
            System.out.println(jxNode);
        }
    }



    /* 3.全文搜索路径 : 全文搜索路径是以“//”开头, 在整个文档中查找符合规则的节点,不需要管目录的结构。

        如果需要查找的是属性值:那么必须以@开头。
  * */
    @Test
    public void test03() throws  Exception {
        //1 得到JXDocument
        Document document = Jsoup.parse(new File(Demo1.class.getResource("/index.html").getPath()), "utf-8");
        JXDocument jxDocument = new JXDocument(document);
//        需求1:直接全文搜索所有的li元素列表并打印
        List<JXNode> list = jxDocument.selN("//li");
//        需求2:直接全文搜索所有的div,再逐层级搜索下面的a元素下的img元素列表并打印
        list = jxDocument.selN("//div/a/img");

//        需求3:直接获取link元素里面href属性的值,注意属性要用@符号
        list = jxDocument.selN("//link/@href");

        for (JXNode jxNode : list) {
            System.out.println(jxNode);
        }

    }

    /*
    条件筛选: 条件筛选全部都需要写在[]里面的


    */

    @Test
    public void test04() throws  Exception {
        //1 得到JXDocument
        Document document = Jsoup.parse(new File(Demo1.class.getResource("/index.html").getPath()), "utf-8");
        JXDocument jxDocument = new JXDocument(document);

//        1)搜索li,属性为class="nav-active"的元素并打印
           List<JXNode> list =  jxDocument.selN("//li[@class='nav-active']");

//        2)搜索li,属性为data-slide-to大于0的元素,再查询data-slide-to的属性值
        list =  jxDocument.selN("//li[@data-slide-to>0]/@data-slide-to");

//        3)搜索a标签,属性为href="login.html"的元素,得到它的文本。

        list =  jxDocument.selN("//a[@href='login.html']/html()");

        for (JXNode jxNode : list) {
            System.out.println(jxNode);

        }

    }



    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值