1

我发现很难找到从 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-中提供的“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 命令,但它们似乎都不起作用。如果我遗漏了什么,请告诉我。

4

3 回答 3

4

这有效:

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

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

例如,这样做:

$nlogConfigXml.configuration.nlog.variable.name

...输出:

LoggingDirectory
于 2013-12-31T06:53:38.227 回答
0

我建议使用 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:)

于 2013-12-31T17:07:55.670 回答
0
$nlogConfigFile = '.\machine.config.nlog.xml'
[XML]$xmlFileContent = Get-Content $nlogConfigFile
$xmlFileContent.configuration.nlog.variable.name

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

于 2021-06-01T10:39:22.820 回答