[英]Read value from XML ignoring any namespaces
我有一个XML文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="publisher" type="KP.Common.Util.XamlConfigurationSection, KP.Common"/>
</configSections>
<publisher>
<p:Publisher xmlns:p="http://schemas.KP.com/xaml/common/notification">
<p:KPLogSubscriber MinimumImportance="Information" />
<p:EventLogSubscriber MinimumImportance="Warning" Source="KPTTY" Log="Application" />
<p:DatabaseMailSubscriber xmlns="http://schemas.KP.com/xaml/data/ef" MinimumImportance="Error" ProfileName = "" Recipients = "administrator@firm.com" Subject = "KPTTY Error" />
</p:Publisher>
</publisher>
</configuration>
我正在尝试使用以下代码读取关键收件人的值:
XmlDocument config = new XmlDocument();
config.Load(configPath);
XmlNode node = config.SelectSingleNode(@"/*[local-name() = 'configuration']/*[local-name() = 'publisher']/*[local-name() = 'Publisher']/*[local-name() = 'DatabaseMailSubscriber']/@Recipients");
Console.WriteLine(node.Value);
但我得到一个异常(节点为空)。 我的Xpath出问题了吗? 我试图忽略xml中可能不存在的任何名称空间。
如果可以使用Linq2Xml
XDocument xDoc = XDocument.Load(fname);
var recipients = xDoc.Descendants()
.First(d => d.Name.LocalName == "DatabaseMailSubscriber")
.Attribute("Recipients")
.Value;
您忘记为“收件人”输入local-name
。 “收件人”属性的前缀为空,表示其名称空间为xmlns="http://schemas.KP.com/xaml/data/ef"
如在“ DatabaseMailSubscriber”元素上所定义。
即,如果您不关心路径,则可以对“任何孩子”简单地使用“ //”:
"//*[local-name() = 'DatabaseMailSubscriber']/@*[local-name() = 'Recipients]"
注意:考虑实际使用名称空间...或按照LB的建议使用XDocument
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.