简体   繁体   中英

Read from XML file using Powershell

I'm finding it hard to figure out a way to retrieve content from XML file. Below is how my xml file looks like. I'm trying to retrieve the complete 'nlog' node. Please help.

<configuration>
<configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, ..."/>
 </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <variable name="LoggingDirectory" value="D:/Logging/"/>
      <include file="${LoggingDirectory}Config/Framework.nlog.xml"/>
  </nlog>
 </configuration>

here is what I have tried so far:

$nlogConfigFile = 'D:\machine.config.nlog.xml'
$nlogConfigXml = new-object xml
$nlogConfigXml.Load($nlogConfigFile);
$nlogConfigXml.PreserveWhitespace = $true

I have used the "Get-XmlNode" function provided in this blog http://blog.danskingdom.com/powershell-functions-to-get-an-xml-node-and-get-and-set-an-xml-elements-value-even-when-the-element-does-not-already-exist/

Get-XmlNode -XmlDocument $nlogConfigXml -NodePath "configuration.configSections.section[@name='nlog']"     ## works OK
Get-XmlNode -XmlDocument $nlogConfigXml -NodePath "configuration.nlog"   ## does NOT work

I have also tried "Select-Xml" , .SelectSingleNode commands but none of them seem to work. Please let me know if I'm missing something.

This works:

$nlogConfigXml = [xml]$(gc "D:\machine.config.nlog.xml")

Then you can navigate $nlogConfigXml using object notation.

For example, doing this:

$nlogConfigXml.configuration.nlog.variable.name

...outputs this:

LoggingDirectory

I would suggest using Select-Xml and XPath. Mind that you need to include namespace info to make it work correctly:

$Xml = [xml]@'
<configuration>
<configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, ..."/>
 </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <variable name="LoggingDirectory" value="D:/Logging/"/>
      <include file="${LoggingDirectory}Config/Framework.nlog.xml"/>
  </nlog>
</configuration>
'@

Select-Xml -Xml $Xml -Namespace @{
    n = "http://www.nlog-project.org/schemas/NLog.xsd"
} -XPath //n:nlog

Namespace definition (hashtable value) is just copy/paste of xmlns . The name you specify (hashtable key) is the same you later have to use in XPath queries as a prefix for XPath elements (as in example: n:nlog )

$nlogConfigFile = '.\machine.config.nlog.xml'
[XML]$xmlFileContent = Get-Content $nlogConfigFile
$xmlFileContent.configuration.nlog.variable.name

Just a little bit different format from the answer before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM