读取和编辑XML内容,并在PowerShell中输出到XML变量

时间:2012-05-30 04:51:39

标签: xml powershell powershell-v2.0

我有类似于以下内容的XML文件内容:

<?xml version="1.0" encoding="utf-8"?>
<Content>
   <FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID>
      <File Path="C:\test.config">
         <Tag TagName="configuration">
            <add Content="One" fileID="${FileID}"/>
            <secondnode Content="Two" fileID="${FileID}">
               <nodeinside>
                  <inneragain fileID="${FileID}"/>
               </nodeinside>
            </secondnode>
            ...
            <diffentnode Content="Infinite" fileID="${FileID}"/>
         </Tag>
      </File>
</Content>

我只需要获取此XML文件内容并编辑(替换存在$ {FileID})行,如下所示

<add fileID="${FileID}"/>

使用以下行中“FileID”的值,并将输出输出到DataType [xml]的变量。

<FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID>

请建议在PowerShell中完成此操作的最佳方式。

1 个答案:

答案 0 :(得分:3)

PS H:\> $xml = [xml]'<?xml version="1.0" encoding="utf-8"?>
    <Content>
    <FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID>
    <File Path="C:\test.config">
        <Tag TagName="configuration">
            <add Content="One" fileID="${FileID}"/>
            <secondnode Content="Two" fileID="${FileID}">
                <nodeinside>                   
                    <inneragain fileID="${FileID}"/>                
                </nodeinside>             
            </secondnode>
            <diffentnode Content="Infinite" fileID="${FileID}"/>          
        </Tag>       
    </File> 
</Content>'

$xml.InnerXml.Replace('${FileID}',$xml.Content.FileID)


<?xml version="1.0" encoding="utf-8"?><Content><FileID>109F2AEA-6D9C-4127-963A-9C71D4155C5D</FileID><File Path="C:\test.config"><Tag TagName="configuration"><add Content="One" fileID="109F2AEA-6D9C-4127-963A-9C71D4155C5D" /><secon
dnode Content="Two" fileID="109F2AEA-6D9C-4127-963A-9C71D4155C5D"><nodeinside><inneragain fileID="109F2AEA-6D9C-4127-963A-9C71D4155C5D" /></nodeinside></secondnode><diffentnode Content="Infinite" fileID="109F2AEA-6D9C-4127-963A-9C
71D4155C5D" /></Tag></File></Content>