zoukankan      html  css  js  c++  java
  • 根据XPath找到某一个特定的节点 Anny

    工作中需要解析到XML文件,发现XPath很神奇。如果能灵活设置XPath,找到某个特定的节点就可以轻而易举了。

    下面的链接大家可以参考一下,主要就是介绍XPath的。

    来自MSDN的介绍:http://msdn.microsoft.com/en-us/library/ms256086.aspx

    便于大家理解,还可以看看下边的两个链接:

    http://www.zvon.org/xxl/XPathTutorial/Output/examples.html

    http://www.w3schools.com/xpath/xpath_syntax.asp

    下面的代码是以后需要继续维护的XmlHelper类,先放到这里。

    代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;

    namespace XmlHelper
    {
    class XmlHelper
    {
    public static void CreateXML(string xml,string fileName)
    {
    XmlDocument xmlDoc
    = new XmlDocument();
    xmlDoc.LoadXml(xml);
    xmlDoc.Save(fileName);
    }

    public static void CreateXML(string fileName, string node, string version, string encoding, string standalone)
    {
    XmlDocument xmlDoc
    = new XmlDocument();
    XmlDeclaration xmlDeclaration
    = xmlDoc.CreateXmlDeclaration(version, encoding, standalone);
    xmlDoc.AppendChild(xmlDeclaration);

    XmlNode root
    = xmlDoc.CreateElement(node);
    xmlDoc.AppendChild(root);

    xmlDoc.Save(fileName);
    }

    public static void CreateXML(string fileName,XmlNode node,string version, string encoding, string standalone )
    {
    XmlDocument xmlDoc
    = new XmlDocument();
    XmlDeclaration xmlDeclaration
    = xmlDoc.CreateXmlDeclaration(version, encoding, standalone);
    xmlDoc.AppendChild(xmlDeclaration);
    xmlDoc.AppendChild(node);
    xmlDoc.Save(fileName);
    }

    /// <summary>
    /// Find xml by xpath according to subelement value
    /// </summary>
    /// <param name="xml"></param>
    /// <param name="xPath">/students/student/name["may"]</param>
    /// <returns></returns>
    public static string FindNodeXmlByXPathWithSubElementValue(string fileName, string xPath)
    {
    string outerXml = string.Empty;
    XmlDocument xmlDoc
    = new XmlDocument();
    xmlDoc.Load(fileName);
    XmlNode node
    = xmlDoc.SelectSingleNode(xPath);
    outerXml
    = node.OuterXml;
    return outerXml;
    }

    /// <summary>
    /// Find specified node by xpath according to subelement value
    /// </summary>
    /// <param name="xml"></param>
    /// <param name="xPath">/students/student/name["may"]</param>
    /// <returns></returns>
    public static XmlNode FindNodeByXPathWithSubElementValue(string fileName, string xPath)
    {
    XmlDocument xmlDoc
    = new XmlDocument();
    xmlDoc.Load(fileName);
    XmlNode node
    = xmlDoc.SelectSingleNode(xPath);
    return node;

    }
    }
    }
  • 相关阅读:
    NET VBCSCompiler.exe占用100%,造成项目卡顿的的解决方法
    C#导出word [无规则表结构+模板遇到的坑]
    mysql允许远程连接的命令
    bootstrap-table的一些基本使用及表内编辑的实现
    在 VS2015+EF6.0中使用Mysql 遇到的坑
    NET使用SuperSocket完成TCP/IP通信
    GRPC在NET上的应用
    NET SignaiR 实现消息的推送,并使用Push.js实现通知
    运维自动化之4
    运维自动化之3
  • 原文地址:https://www.cnblogs.com/limei/p/1751648.html
Copyright © 2011-2022 走看看