You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.Net解析XML提取指定name属性的property值

提取XML中指定Property的值(.NET实现)

没问题,我之前处理过不少SSIS这类带命名空间的XML解析需求,给你两个在.NET里实用的方案,都能轻松提取到name="OpenRowset"的property元素值:

方案1:使用XPath(适合熟悉XPath语法的场景)

因为你的XML带DTS命名空间,这是很多人踩坑的地方,不处理的话解析器根本找不到对应的元素,所以必须先注册命名空间:

using System.Xml;

// 加载XML文档(也可以用LoadXml直接加载字符串形式的XML)
XmlDocument doc = new XmlDocument();
doc.Load("你的XML文件路径");

// 注册DTS命名空间
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("DTS", "www.microsoft.com/SqlServer/Dts");

// 用XPath定位目标元素
XmlNode openRowsetNode = doc.SelectSingleNode("//DTS:ObjectData/pipeline/components/component/properties/property[@name='OpenRowset']", nsManager);

if (openRowsetNode != null)
{
    string targetValue = openRowsetNode.InnerText; // 这里就是你要的"DestinationFile"
    Console.WriteLine(targetValue);
}

如果你的完整XML里有多个DTS:ObjectData节点,想要提取所有符合条件的值,可以用SelectNodes遍历:

XmlNodeList nodes = doc.SelectNodes("//DTS:ObjectData/pipeline/components/component/properties/property[@name='OpenRowset']", nsManager);
foreach (XmlNode node in nodes)
{
    Console.WriteLine(node.InnerText);
}

方案2:使用LINQ to XML(更简洁的现代写法)

LINQ to XML处理命名空间也很直观,代码可读性更高:

using System.Xml.Linq;

// 加载XML(也可以用Parse直接解析字符串XML)
XDocument xDoc = XDocument.Load("你的XML文件路径");

// 声明DTS命名空间
XNamespace dtsNs = "www.microsoft.com/SqlServer/Dts";

// 查询目标值
var openRowsetValue = xDoc.Descendants(dtsNs + "ObjectData")
                          .Elements("pipeline")
                          .Elements("components")
                          .Elements("component")
                          .Elements("properties")
                          .Elements("property")
                          .Where(p => p.Attribute("name")?.Value == "OpenRowset")
                          .Select(p => p.Value)
                          .FirstOrDefault();

if (!string.IsNullOrEmpty(openRowsetValue))
{
    Console.WriteLine(openRowsetValue);
}

要提取所有符合条件的值的话,把FirstOrDefault()换成ToList()即可:

var allValues = xDoc.Descendants(dtsNs + "ObjectData")
                    .Elements("pipeline")
                    .Elements("components")
                    .Elements("component")
                    .Elements("properties")
                    .Elements("property")
                    .Where(p => p.Attribute("name")?.Value == "OpenRowset")
                    .Select(p => p.Value)
                    .ToList();

关键提醒

千万别忘了处理DTS命名空间!如果跳过这一步,不管是XPath还是LINQ to XML都会找不到对应的元素,这是这类XML解析最容易踩的坑。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:02:27