Linq to Xml (1) 创建和查询包含命名空间的XML文档
在项目实施中,我们常常会使用XML作为配置文件,对于普通(不包含命名空间)的XML文档,使用Linq可以很方便地进行读写操作。而对于含有命名空间的XML文档,查询时则需要指定元素所在的命名空间,才能准确获取到结点值。
示例一:下面我使用Linq创建一个包含一个默认命名空间的XML文档:
// 创建含有默认命名空间的Xml文档
XDocument xDoc=new XDocument();
XDeclaration xDeclar=new XDeclaration("1.0","utf-8","yes");
xDoc.Declaration=xDeclar;
XNamespace xns="http://www.netbrother.net";
XElement root=new XElement(xns+"Root",new XElement(xns+"SmartCoder","Tiramisu"));
xDoc.Add(root);
Console.WriteLine(xDoc.Declaration.ToString());
Console.WriteLine(xDoc);
示例中使用字符串对XNamespace赋值,我想大家已经猜到了,在XNamespace的实现中,使用了隐式转换。这里我添加了一个默认的命名空间 xns,示例输出结果如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root xmlns="http://www.netbrother.net">
<SmartCoder>Tiramisu</SmartCoder>
</Root>
示例二:我们还可以通过使用别名的方式,来为XML文档指定多个命名空间。下面是一个包含多个命名空间的示例:
// 创建含有多个命名空间的Xml文档
XDocument xDoc = new XDocument();
XDeclaration xDeclar = new XDeclaration("1.0","utf-8","yes");
xDoc.Declaration = xDeclar;
XNamespace nbNamespace = "http://www.netbrother.net";
XNamespace cuNamespace = "http://www.codeunion.net";
XElement root= new XElement(cuNamespace+"Root",
new XAttribute(XNamespace.Xmlns + "nb",nbNamespace),
new XAttribute(XNamespace.Xmlns + "cu",cuNamespace),
new XElement(cuNamespace + "SmartCoder",
new XElement(nbNamespace + "Coder","Tiramisu"),
new XElement(nbNamespace + "GF","GY")),
new XElement(cuNamespace + "SmartCoder",
new XElement(nbNamespace + "Coder","CD"),
new XElement(nbNamespace + "GF","XL")));
xDoc.Add(root);
Console.WriteLine(xDoc.Declaration.ToString());
Console.WriteLine(xDoc);
此示例中,我声明了两个命名空间对象(cuNamespace和nbNamespace),并将它们追加到 Xmlns 默认命名空间来声明别名(命名空间前缀)。示例中,SmartCoder元素位于cuNamespace命名空间,而其子元素 Coder 和 GF 位于nbNamespace命名空间。此示例输出结果如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<cu:Root xmlns:nb="http://www.netbrother.net" xmlns:cu="http://www.codeunion.net">
<cu:SmartCoder>
<nb:Coder>Tiramisu</nb:Coder>
<nb:GF>MM</nb:GF>
</cu:SmartCoder>
<cu:SmartCoder>
<nb:Coder>CD</nb:Coder>
<nb:GF>XL</nb:GF>
</cu:SmartCoder>
</cu:Root>
下面我们对示例二中的文档进行检索:
// 检索含有命名空间的Xml文档
var smartCoder=xDoc.Descendants(cuNamespace+"SmartCoder").Elements(nbNamespace+"Coder").First();
var gf=smartCoder.Parent.Element(nbNamespace+"GF");
Console.WriteLine(smartCoder.Value);
Console.WriteLine(gf.Value);
检索输出结果如下:
Tiramisu
GY
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构