>我有一个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]"
注意:考虑实际正确使用命名空间...或按照 L.B. 的建议使用XDocument