2017-05-23 7 views
-1

SelectNodes()を使用してXMLファイル内の特定のテキストノードの置換操作を現在実行していて、更新が必要な各ノードを定義しています。これは非常に退屈です(複数の行、毎回同じ置換操作で)。私はそのファイル内のTEXTノードだけを置き換え操作を実行したいと思います。テキストのみのノードの値を置き換えます

これは私が現時点で持っているものです。

$path = "C:\Dump\TEST" 
$Files = Get-Childitem -Path $path -File -Include test_file_1.xml -Name 

foreach ($File in $Files) { 
    $xml = [xml](Get-Content $path\$File) 

    $xml.SelectNodes('//ContactDetailsRow/Notes') | ForEach-Object { 
     $_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b") 
    } 
    $xml.SelectNodes('//AddressesRow/Notes') | ForEach-Object { 
     $_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b") 
    } 

    $xml.Save("$path\$File") 
} 

私はエラーを投げている。このようなXPathを使用してそれを実行しようとしています。

$path = "C:\Dump\TEST" 
$Files = Get-Childitem -Path $path -File -Include test_file_1.xml -Name 

foreach ($File in $Files) { 
    $xml = [xml](Get-Content $path\$File) 
    $xml.SelectNodes('//text()') | ForEach-Object { 
     $_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b") 
    } 
    $xml.Save("$path\$File") 
} 

誤差があるこの

 
You cannot call a method on a null-valued expression. 
At C:\Dump\test12.ps1:14 char:13 
+    $_.'#text' = $_.'#text'.Replace("\", "\\").Replace("`b", "\b") 
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (:) [], RuntimeException 
    + FullyQualifiedErrorId : InvokeMethodOnNull 

これは、例えば、XMLファイルです:

<?xml version="1.0" encoding="UTF-8"?> 
<OrganisationUnits> 
    <OrganisationUnitsRow num="21"> 
    <OrganisationId>ORG1</OrganisationId> 
    <OrganisationName>ORG 1 TEST</OrganisationName> 
    <Addresses> 
     <AddressesRow num="1"> 
     <AddressId>E41002</AddressId> 
     </AddressesRow> 
    </Addresses> 
    <ContactDetails> 
     <ContactDetailsRow num="1"> 
     <ContactValue>[email protected]</ContactValue> 
     <StartDate>2000-03-11</StartDate> 
     <Main>N</Main> 
     <Notes>TEST \ NOTES</Notes> 
     </ContactDetailsRow> 
    </ContactDetails> 
    <Sector>P</Sector> 
    <SectorDesc>Private</SectorDesc> 
    </OrganisationUnitsRow> 
</OrganisationUnits> 
+0

'//テキスト()' - > '// * [テキスト()]' –

答えて

1
PowerShellは、あなたがしようとしているだけで何を支援するために構築されたネイティブコマンドレットを使用してXMLを管理することができます

する。

$path = "C:\Dump\TEST" 
$Files = Get-Childitem -path $path -File -include test_file_1.xml -name 

foreach ($File in $Files) 
{ 
    [xml]$MyXML = Get-Content $File.FullName -raw 
    Select-Xml -XML $MyXML -XPath '//text()'|% {$_.Node.Value = $_.Node.Value -replace '\\','\\' -replace '`b','\b'} 
    $MyXML.Save($File.FullName) 
} 
+0

今すぐ完璧に働いて、@TheMadTechnicianのおかげで – zoomzoomvince

関連する問題