#region 增、删、改操作==============================================

        /// <summary>
/// 追加节点
/// </summary>
/// <param name="filePath">XML文档绝对路径</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <param name="xmlNode">XmlNode节点</param>
/// <returns></returns>
public static bool AppendChild(string filePath, string xPath, XmlNode xmlNode)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(xPath);
XmlNode n = doc.ImportNode(xmlNode, true);
xn.AppendChild(n);
doc.Save(filePath);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 从XML文档中读取节点追加到另一个XML文档中
/// </summary>
/// <param name="filePath">需要读取的XML文档绝对路径</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <param name="toFilePath">被追加节点的XML文档绝对路径</param>
/// <param name="toXPath">范例: @"Skill/First/SkillItem"</param>
/// <returns></returns>
public static bool AppendChild(string filePath, string xPath, string toFilePath, string toXPath)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(toFilePath);
XmlNode xn = doc.SelectSingleNode(toXPath); XmlNodeList xnList = ReadNodes(filePath, xPath);
if (xnList != null)
{
foreach (XmlElement xe in xnList)
{
XmlNode n = doc.ImportNode(xe, true);
xn.AppendChild(n);
}
doc.Save(toFilePath);
}
return true;
}
catch
{
return false;
}
} /// <summary>
/// 修改节点的InnerText的值
/// </summary>
/// <param name="filePath">XML文件绝对路径</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <param name="value">节点的值</param>
/// <returns></returns>
public static bool UpdateNodeInnerText(string filePath, string xPath, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(xPath);
XmlElement xe = (XmlElement)xn;
xe.InnerText = value;
doc.Save(filePath);
}
catch
{
return false;
}
return true;
} /// <summary>
/// 读取XML文档
/// </summary>
/// <param name="filePath">XML文件绝对路径</param>
/// <returns></returns>
public static XmlDocument LoadXmlDoc(string filePath)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
return doc;
}
catch
{
return null;
}
}
#endregion 增、删、改操作 #region 扩展方法===================================================
/// <summary>
/// 读取XML的所有子节点
/// </summary>
/// <param name="filePath">XML文件绝对路径</param>
/// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
/// <returns></returns>
public static XmlNodeList ReadNodes(string filePath, string xPath)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode xn = doc.SelectSingleNode(xPath);
XmlNodeList xnList = xn.ChildNodes; //得到该节点的子节点
return xnList;
}
catch
{
return null;
}
} #endregion 扩展方法

扩                   展

 #region XDocument
//创建XDocument
XDocument xdoc2 = new XDocument();
XElement xel1= new XElement("AA",new XAttribute("mark","mark"));
xel1.Add(new XElement("AA1",""));
xel1.Add(new XElement("AA2", ""));
XElement xel2 = new XElement("AA");
xel2.Add(new XElement("AA1", ""));
xel2.Add(new XElement("AA2", ""));
xel2.Add(new XElement("AAA1", new XElement("AAA1","")));
XElement xel = new XElement("A");
xel.Add(xel2, xel1);
xdoc2.Add(xel); ///循环XDocument
foreach (XElement xElement in xdoc2.Document.Root.Elements())
{
//根据节点名称获取值
string text=xElement.Element("AA1").Value;
//string text2 = xElement.Element("AAA1").Element("AAA1").Value;
//修改节点
xElement.SetElementValue("AA1", "AAA2");
//添加属性
xElement.SetAttributeValue("name", "name");
//设置值
xElement.Element("AA1").SetValue("");
}
#endregion #region XmlDocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("D://Pro//EGP410_5//Test//XMLFile1.xml");
//循环XmlDocument
XmlNodeList xmlNode= xmlDoc.DocumentElement.ChildNodes;
foreach (XmlNode item in xmlNode)
{
}
//查询
string str = xmlDoc.DocumentElement.SelectSingleNode("DTrue").InnerText;
str = xmlDoc.DocumentElement.SelectSingleNode("/Result/DTrue").InnerText;
//修改
xmlDoc.DocumentElement.SelectSingleNode("DTrue").InnerText = "DTrue";
//获取属性
str = xmlDoc.DocumentElement.GetAttribute("mark");
//修改属性
xmlDoc.DocumentElement.SetAttribute("mark", "");
//保存。
xmlDoc.Save("D://Pro//EGP410_5//Test//XMLFile1.xml"); #endregion

XDocument和XmlDocument的创建 修改 查询 属性 循环等操作

xml的读

XElement xele1 = XElement.Load(Path);  //根据路径获取xml元素

XElement xele2 = XElement.Parse("");      //根据字符串获取xml元素

XmlDocument doc = new XmlDocument();

doc.LoadXml(xele1.ToString());        //根据字符串获取xml文档

doc.Load(Path);                 //根据路径获取xml文档

xml的取xpath

XDocument doc = XDocument.Load(Path);
 XElement root = doc.Element("DATASET").Element("BUYER_NAME");

string text = xnode.InnerText;           //获取值(方式一)

XmlNode node=doc2.SelectSingleNode("//DATASET/BUYER_NAME");     //获取单个xmlnode 不用循环

XmlNodeList nodes = doc.SelectNodes("//A/A01/A0101");   // 双斜线表示不从根目录取(获取多个xmlnode 所以要采用循环)

foreach (XmlNode de in nodes)
  {
        var dsd = de.InnerText;      //获取值(方式二)
  }

xml的写包括写入备注 (linq to xml)

        public static void CreateXmlByLink()
{
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("提示"),
new XElement("root",
new XElement("A",
new XElement("A01",
new XElement("A0101", "货物A0101"),
new XComment("提示"),
new XAttribute("V1", ""),
new XElement("A0102", "货物A0102"),
new XElement("A0103",
new XAttribute("V1", ""),
new XElement("A010301",new XAttribute("V1", ""), "货物A010301"),
new XElement("A010302", "货物A010302")
)
),
new XElement("A01",
new XElement("A0101", "货物A0101"),
new XElement("A0102", "货物A0102"),
new XElement("A0103",
new XElement("A010301", "货物A010301"),
new XElement("A010302", "货物A010302")
)
)
), new XElement("B",
new XElement("A01",
new XElement("A0101", "货物A0101"),
new XElement("A0102", "货物A0102"),
new XElement("A0103",
new XElement("A010301", "货物A010301"),
new XElement("A010302", "货物A010302")
)
),
new XElement("A01",
new XElement("A0101", "货物A0101"),
new XElement("A0102", "货物A0102"),
new XElement("A0103",
new XElement("A010301", "货物A010301"),
new XElement("A010302", "货物A010302")
)
)
), new XElement("C",
new XElement("A01",
new XElement("A0101", "货物A0101"),
new XElement("A0102", "货物A0102"),
new XElement("A0103",
new XElement("A010301", "货物A010301"),
new XElement("A010302", "货物A010302")
)
),
new XElement("A01",
new XElement("A0101", "货物A0101"),
new XElement("A0102", "货物A0102"),
new XElement("A0103",
new XElement("A010301", "货物A010301"),
new XElement("A010302", "货物A010302")
)
)
)
)
);
xdoc.Save(Path);
}

添加节点

XmlNode node= doc.SelectNodes("//A/A01/A0101")[0];     //修改/添加 路径下   的第一个节点

XmlElement no = doc.CreateElement("newNode");
no.InnerText = "新增节点1";
node.AppendChild(no);  //新增

修改、删除xml节点

foreach (XmlNode item in node)
{
XmlElement xe = (XmlElement)item ;
if (xe.GetAttribute("A") == "A01")
{
xe.SetAttribute("A","A");  //修改

xe.Remove("A");  //修改
}
}

xml 映射到页面table(参照http://www.w3school.com.cn/tiy/t.asp?f=xmle_display_table_1)

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style>
.a {
border: 1px solid red;
}
</style>
<script type="text/javascript">
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "test.xml", false);
xmlhttp.send(); xmlDoc = xmlhttp.responseXML; var html = "<table border='1' class=\"a\" style=\"width:100px;height:20px\">";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i < x.length; i++) {
html = html + "</td><td>";
html = html + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
html = html + "</td><td>";
html = html + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue; html = html + "</td><td>";
html = html + x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
html = html + "</td></tr>";
}
html = html + "</table>";
document.write(html)
</script>
</head>
<body>
</body>
</html>

C# xml 读xml、写xml、Xpath、Xml to Linq、xml添加节点 xml修改节点的更多相关文章

  1. 使用DOM解析XML文件,、读取xml文件、保存xml、增加节点、修改节点属性、删除节点

    使用的xml文件 <?xml version="1.0" encoding="GB2312" ?> <PhoneInfo> <Br ...

  2. c#操作xml的代码(插入节点、修改节点、删除节点等)

    bookstore.xml文件内容: 复制代码代码示例: <?xml version="1.0" encoding="gb2312"?><bo ...

  3. 用TinyXml做XML解析示例 TinyXml查找唯一节点及修改节点操作

    // 读者对象:对TinyXml有一定了解的人.本文是对TinyXml工具的一些知识点的理解. // 1 TinyXml中对TiXmlNode进行了分类,是用一个枚举进行描述的. // enum No ...

  4. XML——读与写

    XML写入 private static void writeXml() { using (XmlTextWriter xml = new XmlTextWriter(@"C:\Users\ ...

  5. DOM解析xml实现读、写、增、删、改

    qt提供了三种方式解析xml,不过如果想实现对xml文件进行增.删.改等操作,还是DOM方式最方便. 项目配置 pro文件里面添加QT+=xml include <QtXml>,也可以in ...

  6. XML文件的写,集合XML序列化(写)。XML文件的读,递归遍历

    XML文件:必须要有一个节点.检验xml文件,可以用浏览器打开,能打开表示对,否则错. 处理方法: DOM:XmlDocument文档对象模型 Sax(事件驱动,XmlReader) XmlSeria ...

  7. XML文档的读、写

    代码: XmlDocument doc = new XmlDocument(); doc.Load("Books.xml"); //1.加载要读取的XML文件 //要想看到数据得先 ...

  8. 用JDK自带的包来解析XML文件(DOM+xpath)

    DOM编程不要其它的依赖包,因为JDK里自带的JDK里含有的上面提到的org.w3c.dom.org.xml.sax 和javax.xml.parsers包就可以满意条件了.(1)org.w3c.do ...

  9. 转载--- SQL Server XML基础学习之<4>--XPath

    T-SQL 支持用于查询  XML 数据类型的 XQuery 语言. XQuery 基于现有的 XPath 查询语言,并支持更好的迭代.更好的排序结果以及构造必需的  XML 的功能. 所以我们本章先 ...

随机推荐

  1. Linux下安装Python3的django并配置mysql作为django默认数据库(转载)

    我的操作系统为centos6.5 1  首先选择django要使用什么数据库.django1.10默认数据库为sqlite3,本人想使用mysql数据库,但为了测试方便顺便要安装一下sqlite开发包 ...

  2. sdk(输入驱动物体 驱动属性 被驱动物体 被驱动属性 驱动数值 一键搞定驱动),当你的目标体很多展开会卡的时候使用这个

    import  maya.cmds  as  mc def   sdksomething( sdk_obj="",                    sdkAttr=" ...

  3. 文件IO 相关的包:java.io文件——API

    文件IO 相关的包:java.io文件——API 1.Java.io.File类的使用(1)两种路径绝对路径:相对于当前路径:当前为 “工程名”(2)File类创建,对象为一个文件/目录,可能存在或不 ...

  4. docs actifio

    http://docs.actifio.com/ https://www.actifio.com/resource-center/

  5. c#函数地址传入c++

    c# private delegate void ValidateEvent(int eventCode); private static void ValidateEventCallback(int ...

  6. Centos7使用yum快速安装ansible

    ansible功能简介:ansible可以实现批量系统配置.批量软件部署.批量文件拷贝.批量运行命令等功能.主要基于ssh实现连接各个被控制端 yum默认安装的ansible,常用的配置文件有两个,一 ...

  7. Computer Graphics Principles And Practice (James Foley / Andries Van Dam / Morgan McGuire / David Sklar / James D. Foley 著)

    1 Introduction 2 Introduction to 2D Graphics Using WPF 3 An Ancient Renderer Made Modern 4 A 2D Grap ...

  8. C goto

    http://c.biancheng.net/view/266.html 当程序遇到 goto 后, 会无条件跳转到标签后出,然后程序按照顺序执行 例子: #include <stdio.h&g ...

  9. Python 模块源

    1.官方:https://pypi.org/ 2.LFD UCI :https://www.lfd.uci.edu/~gohlke/pythonlibs/ 4.清华源:https://pypi.tun ...

  10. Day14全局变量与局部变量

    列表的所有方法都可以用,如remove  clear 为了避免容易出错,全局变量名用大写,局部变量名用小写  nonlocal指上一级的name