【问题标题】:Reading an XML File using an XML object results in missing entries使用 XML 对象读取 XML 文件会导致缺少条目
【发布时间】:2020-07-31 04:26:20
【问题描述】:

我已获得要更新的 XML 文件,但在使用 XML 对象读取文件时,多个条目丢失。

XML 文件(注意两个 sectionGroup)

<configuration>
  <configSections>
    <sectionGroup name="Albert" type="Male, Outlook=neutral" >
         <section name="Bobby" type="Male, Outlook=happy"/>
         <section name="Cathy" type="Female, Outlook=neutral"/>
         <section name="David" type="Male, History=Yes"/>
         <sectionGroup name="Mark" type="Male, Outlook=happy" >
              <section name="Matt" type="Male, Outlook=neutral"/>
         </sectionGroup>
    </sectionGroup>
  </configSections>
</configuration>

脚本:

[XML] $xmlObj=Get-Content "C:\temp\infile.xml" -Raw

foreach ($elem in $xmlObj.configuration.configSections.sectionGroup.section)
    {
    Write-Host ("=> {0}='{1}'" -f $elem.name, $elem.type) 
    }

输出:

=>  Bobby='Male, Outlook=happy'
=>  Cathy='Female, Outlook=neutral'
=>  David='Male, History=Yes'

请注意,不包括名字 (Albert) 或第二部分中的两个名字 (Mark, Matt)。

我无法更改多个 XML 文件,所以:

  1. 需要对代码进行哪些更改才能查看所有条目?
  2. 写回它们时,是否还需要进行其他更改?

【问题讨论】:

    标签: json xml powershell


    【解决方案1】:

    使用 XPath 表达式选择所有 &lt;section&gt; 元素,无论位置如何:

    foreach($elem in $xmlObj.SelectNodes('//section')){
      # work with $elem
    }
    

    【讨论】:

      【解决方案2】:

      好的,解决它。每个都是不同的部分,需要指定。这将返回所有 6

      $xmlObj.configuration.configSections.sectionGroup  | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }
      
      $xmlObj.configuration.configSections.sectionGroup.section | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }
      
      $xmlObj.configuration.configSections.sectionGroup.sectionGroup | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }
      
      $xmlObj.configuration.configSections.sectionGroup.sectionGroup.section | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2020-11-28
        • 2013-06-03
        • 2023-03-10
        • 2021-11-21
        相关资源
        最近更新 更多