如何在C#中选择具有给定属性值的节点?

时间:2012-08-31 02:56:57

标签: c# xml xpath

我只想选择具有“name”属性value ='syslog'的目标元素。无论如何,我总是得到一个NullReferenceException。任何人都可以帮我弄清问题是什么?

----------------我的代码----------------------------- --------------

XmlNode root = _configFile.DocumentElement; // root is not none, and is correct.
XmlNode syslogNode = root.SelectSingleNode("descendant::targets/target[@name='syslog']"); // the syslogNode is null

-----------------我的XML文件--------------------------- -----------

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <extensions>
    <add assembly="NLog.Targets.Syslog" />
  </extensions>

  <targets>
    <target name="syslog" xsi:type="Syslog" syslogserver="127.0.0.1" port="514" facility="Local7" />
    <target name="file" xsi:type="File" layout="${level} | ${longdate} | ${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true} | ${message} ${exception:format=tostring}"
            fileName="${specialfolder:folder=LocalApplicationData}/Televic Conference/CoCon/Log/server_log_${shortdate}.txt"
            archiveFileName="${specialfolder:folder=LocalApplicationData}/Televic Conference/CoCon/Log/Archives/server_log.{#}.txt"
            archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="20" concurrentWrites="true" keepFileOpen="false"/>
    <target name="console" xsi:type="ColoredConsole" layout="${longdate}: ${message}"/>
    <target name="debug" xsi:type="OutputDebugString" layout="${longdate}: ${message}"/>
  </targets>

  <rules>
    <logger name="*" minLevel="Trace" appendTo="syslog"/>
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

2 个答案:

答案 0 :(得分:1)

使用LINQ2XML ..Its cool

XElement doc = XElement.Load("yourStream.xml");
XNamespace g = "http://www.nlog-project.org/schemas/NLog.xsd";//global namespace g

foreach (var itm in doc.Descendants(g + "targets").Where(x=>x.Atrribute("name").Value=="syslog"))
{
itm;//your required node
}

答案 1 :(得分:0)

您的文档具有默认命名空间 - 您需要考虑它或在XPath表达式中忽略它。见这里:

XPath select node with namespace