1

I just want to select the target element which has "name" attribute value = 'syslog'. Anyway, I always get an NullReferenceException. Can anyone help me to figure out what is the problem?

---------------- My code -------------------------------------------

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

-----------------My XML file --------------------------------------

<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>
Joe SHI
  • 1,734
  • 4
  • 20
  • 39

2 Answers2

1

Use 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
}
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Your document has a default namespace- you need to either take it into account or ignore it in your XPath expression. See here:

XPath select node with namespace

Community
  • 1
  • 1
nitzmahone
  • 13,720
  • 2
  • 36
  • 39