【问题标题】:Read from XML file using Powershell使用 Powershell 从 XML 文件中读取
【发布时间】:2014-01-18 03:20:08
【问题描述】:

我发现很难找到从 XML 文件中检索内容的方法。下面是我的 xml 文件的样子。 我正在尝试检索完整的“nlog”节点。请帮忙。

<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>

这是我迄今为止尝试过的:

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

我已经使用了本博客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”功能

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

我也尝试过 "Select-Xml" 、 .SelectSingleNode 命令,但它们似乎都不起作用。 如果我遗漏了什么,请告诉我。

【问题讨论】:

    标签: xml powershell powershell-ise


    【解决方案1】:

    这行得通:

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

    然后您可以使用对象表示法导航$nlogConfigXml

    例如,这样做:

    $nlogConfigXml.configuration.nlog.variable.name
    

    ...输出这个:

    LoggingDirectory
    

    【讨论】:

    • 嗨,如何使用此模型按属性访问元素?例如:检索 name='nlog' 的部分?
    • @CrazyFrog - 我添加了一个示例。
    • 对于 Powershell 新手(我目前是其中之一) - gcGet-Content 的缩写,而不是 垃圾收集器
    【解决方案2】:

    我建议使用 Select-Xml 和 XPath。请注意,您需要包含命名空间信息才能使其正常工作:

    $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
    

    命名空间定义(哈希表值)只是 xmlns 的复制/粘贴。 您指定的名称(哈希表键)与您以后必须在 XPath 查询中用作 XPath 元素的前缀的名称相同(例如:n:nlog

    【讨论】:

      【解决方案3】:
      $nlogConfigFile = '.\machine.config.nlog.xml'
      [XML]$xmlFileContent = Get-Content $nlogConfigFile
      $xmlFileContent.configuration.nlog.variable.name
      

      与之前的答案格式略有不同。

      【讨论】:

      • 这不能正常工作它总是抛出错误。 @enigmitavity 指定的答案很有帮助,并且按预期工作。
      猜你喜欢
      • 2010-12-21
      • 2011-08-22
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多