【问题标题】:Powershell - Search XML for Element with certain name and add them to another XML documentPowershell - 在 XML 中搜索具有特定名称的元素并将它们添加到另一个 XML 文档
【发布时间】:2020-05-15 07:13:30
【问题描述】:

我正在尝试在 XML 文档中搜索属性字段中具有特定字符串的条目。如果该字符串存在,我想将整个元素复制到另一个具有相同结构的 xml。

到目前为止,我能够找到元素并将它们保存到数组中。我在将每个文件保存到 XML 时遇到问题。

两种 XML 文件结构:

> <?xml version="1.0" encoding="utf-8"?> 
  <ClassConfiguratorConfig
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xmlns:xsd="http://www.w3.org/2001/XMLSchema">   
    <Section>
>     <SProperties>
>       <SProperty Name="C_ITEM1VALUE" Value="1" />
>       <SProperty Name="C_ITEM2VALUE" Value="5" />
>       <SProperty Name="C_ITEM3VALUE" Value="20" />
>       <SProperty Name="C_ITEM4VALUE" Value="100" />
>       <SProperty Name="C_ITEM1TYPE" Value="0" />
>       <SProperty Name="C_ITEM2TYPE" Value="0" />
>       <SProperty Name="C_ITEM3TYPE" Value="0" />
>       <SProperty Name="C_ITEM4TYPE" Value="0" />
>       <SProperty Name="START_RETURNIMMEDIATELY" Value="FALSE" />
>       <SProperty Name="SUPER_EXITTIMEOUT" Value="10" />
>     </SProperties>   
    </Section> 
  </ClassConfiguratorConfig>

当前代码用于查找 SProperty1.xml 中 Name 属性包含“C_ITEM”的所有 SProperty 实例。然后将其所有条目添加到 SProperty2.xml

[xml]$XML1 = Get-Content "C:\Temp\SProperty1.XML"
[xml]$XML2 = Get-Content "C:\Temp\SProperty2.XML"

$Node1 = $XML1.ClassConfiguratorConfig.Section.SProperties
$Node2 = $XML2.ClassConfiguratorConfig.Section.SProperties

$Nodes = $XML1.SelectNodes("//SProperties/*[@*[contains(.,'C_ITEM')]]")

foreach ($Node in $Nodes){
       $XML2.CreateElement('SProperty')
       $Child.SetAttribute('Name',"$Node.Name")
       $Child.SetAttribute('Value',"$Node.Value")
       $Node2.AppendChild($Child)
   }

当 for 循环过程由于某种原因我得到以下输出时:

Name                       Value
----                       -----
System.Xml.XmlElement.Name System.Xml.XmlElement.Value
System.Xml.XmlElement.Name System.Xml.XmlElement.Value
System.Xml.XmlElement.Name System.Xml.XmlElement.Value
System.Xml.XmlElement.Name System.Xml.XmlElement.Value
System.Xml.XmlElement.Name System.Xml.XmlElement.Value
System.Xml.XmlElement.Name System.Xml.XmlElement.Value

任何帮助将不胜感激

【问题讨论】:

  • 如果您可以显示在这种情况下您期望的输出,问题可能会得到改善?就像一个部分说我希望输出看起来像这样:EXPECTED OUTPUT的示例代码

标签: arrays xml powershell copy


【解决方案1】:

这是因为当你在变量周围使用“”时,你没有在 $() 中包含你的值。

       $child = $XML2.CreateElement('SProperty')
       $Child.SetAttribute('Name',"$($Node.Name)")  
       $Child.SetAttribute('Value',"$($Node.Value)")

('Name',"$Node.Name") 不正确,如果您试图从 $Node 获取 Name 的值。您实质上是将属性名称设置为"$Node" + ".Node",将值设置为"$Node" + ".Value"

为了让 powershell 知道您正在尝试访问 Node 的 Name 或 Value 属性,您必须在 "" 中使用完整的变量,这是通过使用 @() 封装 $variable 和属性名称来完成的。所以,"$($Node.Name)" 会起作用。

用法应该是这样的,('Name',"$($Node.Name)")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2013-03-17
    • 2017-07-22
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多