2017-05-19 2 views
0

xml 파일에는 백 슬래시로 특정 문자를 대체해야합니다. XML을 사용하는 응용 프로그램은 여러 가지 이유로 필요합니다. 로powershell - xml 노드 사이의 문자를 바꿉니다.

그래서 나는 \ n 캐리지 리턴에 의해 대체 될 줄 바꿈 f를 \로 대체 할 \ 용지 공급으로 대체 할 \ " 백 슬래시 \로 "를 교체하려면 다음 chnages을 할 필요가 탭으로 바꿔야합니다. \ t 백 스페이스로 대체됩니다. \ b

이렇게 매우 간단한 xml 스 니펫은 다음과 같습니다.

<?xml version="1.0" encoding="UTF-8"?> 
     <ContactDetailsRow num="1"> 
     <Notes>This a test for special characters that need to be replaced 
Ampersand - &amp; 
Double Quote - &quot; 
Forward Slash -/
Back Slash - \ 
Less Than - &lt; 
Greater Than - &gt; 
Question Mark - ? 
Tab  </Notes> 
     </ContactDetailsRow> 

대체품이있는 GC를 기반으로 지금까지 시도한 기능이 작동하지 않는 것 같습니다.

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

foreach ($File in $Files) 
{ 
    write-host "=== FILE is $File ===" -ForegroundColor "White" 
    $xml = [xml](Get-Content $path\$File) 

    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '&quot;', '\&quot;' #doubel quote 
    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '`n;', '`\n'   #newline 
    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '`f' , '`\f'   #form feed 
    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '`r' , '`\r'   #carriage return 
    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '`t' , '`\t'   #tab 
    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '`b' , '`\b'   #backspace 
    $xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes -replace '`\' , '`\\'   #back slash 
    write-host $xml.ContactDetailsRow.Notes 

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

또한 선택 노드로 시도했지만 그 중 하나도 작동하지 않았습니다.

$xml.SelectNodes('//text()') | ForEach-Object { 
    $_.Value = ($_.Value -replace "&quot;" , "\&quot;") 
} 

답변

1

XML 노드 값은 유형 문자열입니다. .Replace() 메소드 만 사용할 수 있습니다. 당신이 XML로 파일 내용을 읽을 경우

$xml.ContactDetailsRow.Notes = $xml.ContactDetailsRow.Notes.Replace("`t" , '\t') 

또한 PowerShell은 &quot; 같은 표현을 해석합니다.

관련 문제