Modify XML Parent Attributes iterating through Child attributes using powershell

后端 未结 2 1546
北海茫月
北海茫月 2020-12-20 08:15

So I have the following xml (items.xml) and I want to find the attributes of the child node item iterate through the attributes and if I find similar attributes at parent no

2条回答
  •  太阳男子
    2020-12-20 09:17

    Since your title mentions Modify XML, consider XSLT, the special purpose language designed solely to transform XML files. Specifically, you can run the Identity Transform (copy document as is) and then keep only the attributes that match attribute names of ancestor::model (grandparent) using the and conditionals. PowerShell can create an object of .NET Framework class, System.Xml.Xsl.XslCompiledTransform, to run XSLT 1.0 scripts.

    XSLT (save as .xsl to be passed as argument in PowerShell)

    
    
    
    
      
      
         
           
         
      
    
      
          
                 
         
                     
           
             
      
    
    
    

    PowerShell (general script for any XML input and XSLT 1.0 script)

    param ($xml, $xsl, $output)
    
    if (-not $xml -or -not $xsl -or -not $output) {
        Write-Host "& .\xslt.ps1 [-xml] xml-input [-xsl] xsl-input [-output] transform-output"
        exit;
    }
    
    trap [Exception]{
        Write-Host $_.Exception;
    }
    
    $xslt = New-Object System.Xml.Xsl.XslCompiledTransform;
    
    $xslt.Load($xsl);
    $xslt.Transform($xml, $output);
    
    Write-Host "generated" $output;
    
    Read-Host -Prompt "Press Enter to exit";
    

    Command line call

    Powershell.exe -File "C:\Path\To\PowerShell\Script.ps1"^
     "C:\Path\To\Input.xml" "C:\Path\To\XSLTScript.xsl" "C:\Path\To\Ouput.xml"
    

    Output

    
    
      
        
          
        
      
      
        
          
        
      
      
        
          
        
      
    
    

提交回复
热议问题