【问题标题】:SelectSingleNode returned null valueSelectSingleNode 返回空值
【发布时间】:2021-10-14 20:34:06
【问题描述】:

我正在尝试使用 PowerShell 修改 xml 文件。当我尝试使用函数 SelectSingleNode 选择目标节点时,它返回 null。

我在堆栈溢出中搜索,发现很多答案都说我需要将namespaceManager传递给SelectSingleNode。我试过了,但还是没有运气。

这里是我需要修改的目标xml文件:

<PolicyMetadata xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2012/04/ADFS">
  <RequireFreshAuthentication>false</RequireFreshAuthentication>
  <IssuanceAuthorizationRules>
    <Rule>
      <Conditions>
        <Condition i:type="GroupMembershipCondition">
          <Operator>Equals</Operator>
          <Values>
            <Value>S-1-5-21-297304416-3458697141-814752582-1120</Value>
          </Values>
        </Condition>
        <Condition i:type="MultiFactorAuthenticationCondition">
          <Operator>IsPresent</Operator>
          <Values />
        </Condition>
      </Conditions>
    </Rule>
    <Rule>
      <Conditions>
        <Condition i:type="LocationCondition">
          <Operator>Equals</Operator>
          <Values>
            <Value>192.168.1.0/24</Value>
            <Value>1.1.1.1</Value>
            <Value>2.2.2.2</Value>
          </Values>
        </Condition>
      </Conditions>
    </Rule>
  </IssuanceAuthorizationRules>
</PolicyMetadata>

我正在尝试选择 Condition i:type="LocationCondition" 下的节点 Values

这是我使用的 PowerShell 脚本:

$xml = New-Object Xml
$xml.Load("C:\temp\policy1.xml")
$nsmgr = new-object Xml.XmlNamespaceManager($xml.NameTable)
$nsmgr.AddNameSpace("x", "http://microsoft.com/GroupPolicy/GPOOperations/MigrationTable")
$nsmgr.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance")
$xml.SelectSingleNode("//x:Condition[@i:type='LocationCondition']/Values",$nsmgr)
$xml.SelectSingleNode("//Condition[@i:type='LocationCondition']/Values",$nsmgr)

任何想法为什么它不起作用?

【问题讨论】:

  • "...我正在尝试修改 xml 文件..." 请编辑您的问题,并添加以下内容:(1) 输入 XML,(2) 所需输出,(3)修改逻辑。
  • 您的默认命名空间在命名空间管理器中没有前缀。您需要添加它,然后在 XPATH 中为所有节点添加前缀。如果您不关心命名空间,那么您可以选择($xml.PolicyMetadata.IssuanceAuthorizationRules.Rule.Conditions.Condition | where type -eq 'LocationCondition').Values
  • @YitzhakKhabinsky 我不是在寻求修改该文件的帮助。这就是我要自己努力达到的目标。在这篇文章中,我只需要帮助来弄清楚如何在 PowerShell 中使用 SelectSingleNode。所以,我只是介绍一下为什么我需要这个函数为我工作的背景。

标签: xml powershell


【解决方案1】:

你快到了;你只需要稍微不同地管理你的命名空间。试试这样:

$nsmgr.AddNamespace("x", "http://schemas.datacontract.org/2012/04/ADFS")
$nsmgr.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance")

$targets = $xml.SelectSingleNode('//x:Condition[@i:type="LocationCondition"]//x:Values',$nsmgr)
$targets

看看它是否有效。

【讨论】:

  • 谢谢你,杰克,它就像一个魅力。我没有意识到“虚拟命名空间”必须与 xml 文件中的真实命名空间相匹配。 (在其他回复中,他们称它为 dummy namespace,所以我认为它可以是任何东西)我不知道的另一件事是 Xpath 表达式中的子元素也需要命名空间前缀。
  • @StevenLee-MSFT 正如他们所说,生活和学习!很高兴它对你有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多