C#使用XDocument操作XML格式数据
|
admin
2025年7月24日 14:56
本文热度 1205
|
XDocument是C#中LINQ to XML的核心类,它提供了一种更现代、更直观的方式来处理XML数据。相比传统的XmlDocument,XDocument更加简洁易用。开发软件:Visual Studio 2019
核心组件:LINQ to XML (System.Xml.Linq)辅助组件:System.Xml, System.IO一.创建一个C#窗台程序用来演示C#操作XML,生成XML格式数据<?xml version="1.0"?><res> <Code>0</Code> <Desc>成功</Desc> <Info> <Code>1</Code> <Name>小明</Name> </Info> <Info> <Code>2</Code> <Name>大明</Name> </Info> <List> <Info> <Code>1</Code> <Name>北京</Name> </Info> <Info> <Code>2</Code> <Name>上海</Name> </Info> </List></res>
string[] username = { "小明", "大明" }; string[] city = { "北京", "上海" };
XDocument doc = new XDocument(); XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", null); doc.Declaration = xDeclaration;
XElement xEres = new XElement("res"); XElement xDCode = new XElement("Code", "0"); XElement xDDesc = new XElement("Desc", "成功"); xEres.Add(xDCode); xEres.Add(xDDesc);
for (int i = 0; i < username.Length; i++) { XElement xEInfo = new XElement("Info");
XElement Code = new XElement("Code", (i + 1).ToString()); xEInfo.Add(Code);
XElement Name = new XElement("Name", username[i]); xEInfo.Add(Name);
xEres.Add(xEInfo); }
XElement List = new XElement("List"); for (int i = 0; i < city.Length; i++) { XElement xEInfo = new XElement("Info");
XElement Code = new XElement("Code", (i + 1).ToString()); xEInfo.Add(Code);
XElement Name = new XElement("Name", city[i]); xEInfo.Add(Name);
List.Add(xEInfo); } xEres.Add(List);
doc.Add(xEres);
richTextBox1.Text = XmlToString(doc).ToString();
public static string XmlToString(XDocument doc) { string xmlString; using (var writer = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(writer)) { doc.WriteTo(xmlWriter); } xmlString = writer.ToString(); } return xmlString; }

XDocument doc = XDocument.Parse(richTextBox1.Text); XElement res = doc.Element("res");
string str_Code = res.Element("Code").Value; string str_Desc = res.Element("Desc").Value; richTextBox2.AppendText("Code:" + str_Code); richTextBox2.AppendText("-"); richTextBox2.AppendText("Desc:" + str_Desc); richTextBox2.AppendText("\r\n");
var xEInfos = res.Elements("Info");
foreach (XElement info in xEInfos) { string str_InfoCode = info.Element("Code").Value; string str_InfoName = info.Element("Name").Value;
richTextBox2.AppendText("userCode:" + str_InfoCode); richTextBox2.AppendText("-"); richTextBox2.AppendText("userName:" + str_InfoName); richTextBox2.AppendText("\r\n"); }
XElement List = res.Element("List"); var Infos = List.Elements("Info");
foreach (XElement info in Infos) { string str_InfoCode = info.Element("Code").Value; string str_InfoName = info.Element("Name").Value;
richTextBox2.AppendText("cityCode:" + str_InfoCode); richTextBox2.AppendText("-"); richTextBox2.AppendText("cityName:" + str_InfoName); richTextBox2.AppendText("\r\n"); }
该文章在 2025/7/24 14:56:23 编辑过