programing

XML 저장 및 형식 보존을 위한 Powershell

javajsp 2023. 9. 16. 08:40

XML 저장 및 형식 보존을 위한 Powershell

XML 파일로 읽고 요소를 수정한 후 파일에 다시 저장하고 싶습니다.포맷을 유지하면서 라인 터미네이터(CRLF 대 LF)를 계속 일치시키는 가장 좋은 방법은 무엇입니까?

이것이 제가 가지고 있는 것이지만, 그것은 그렇게 하지 못합니다.

$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true
# Change some element
$xml.Save($fileName)

문제는 LF와 CRLF를 혼합한 후에 추가적인 새로운 라인(xml의 빈 라인이라고 함)이 제거된다는 것입니다.

PowerShell [xml] 개체를 사용하고 설정할 수 있습니다.$xml.PreserveWhitespace = $true, 또는 .NET을 사용하여 동일한 작업을 수행합니다.XmlDocument:

# NOTE: Full path to file is *highly* recommended
$f = Convert-Path '.\xml_test.xml'

# Using .NET XmlDocument
$xml = New-Object System.Xml.XmlDocument
$xml.PreserveWhitespace = $true

# Or using PS [xml] (older PowerShell versions may need to use psbase)
$xml = New-Object xml
$xml.PreserveWhitespace = $true
#$xml.psbase.PreserveWhitespace = $true  # Older PS versions

# Load with preserve setting
$xml.Load($f)
$n = $xml.SelectSingleNode('//file')
$n.InnerText = 'b'
$xml.Save($f)

전화를 걸기 전에 Preserve Whitespace를 설정해야 합니다.XmlDocument.Load아니면XmlDocument.LoadXml.

참고: 이것은 XML 특성 사이의 공백을 보존하지 않습니다.XML 특성의 공백이 보존되는 것 같지만 그 사이에는 없습니다.이 문서는 "백공간 노드"를 보존하는 것에 대해 설명합니다.node.NodeType = System.Xml.XmlNodeType.Whitespace속성이 아닙니다.

XmlDocument에서 Save 메서드를 호출한 후 텍스트 노드에 대해 LF로 변환되는 CRLF를 수정하려면 XmlWriterSettings 인스턴스를 사용할 수 있습니다.MilesDavies192s 응답과 동일한 XmlWriter를 사용하지만 인코딩을 utf-8로 변경하고 들여쓰기를 유지합니다.

$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true

# Change some element

#Settings object will instruct how the xml elements are written to the file
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Indent = $true
#NewLineChars will affect all newlines
$settings.NewLineChars ="`r`n"
#Set an optional encoding, UTF-8 is the most used (without BOM)
$settings.Encoding = New-Object System.Text.UTF8Encoding( $false )

$w = [System.Xml.XmlWriter]::Create($fileName, $settings)
try{
    $xml.Save( $w )
} finally{
    $w.Dispose()
}

xml을 읽을 때 기본적으로 무시된 빈 줄을 읽을 때, 그 줄을 보존하기 위해 변경할 수 있습니다.PreserveWhitespace파일 읽기 전 속성:

XmlDocument 개체를 만들고 PresureWhitespace를 구성합니다.

$xmlDoc = [xml]::new()
$xmlDoc.PreserveWhitespace = $true

문서를 로드합니다.

$xmlDoc.Load($myFilePath)

아니면

$xmlDoc.LoadXml($(Get-Content $myFilePath -Raw))

XmlWriter를 사용하여 저장할 경우 기본 옵션은 공백이 두 개 있는 들여쓰기와 줄 끝을 CR/LF로 바꾸는 것입니다.기록기를 만든 후에 이러한 옵션을 구성하거나 필요에 따라 구성된 XmlSettings 개체로 기록기를 만들 수 있습니다.

    $fileXML = New-Object System.Xml.XmlDocument

    # Try and read the file as XML. Let the errors go if it's not.
    [void]$fileXML.Load($file)

    $writerXML = [System.Xml.XmlWriter]::Create($file)
    $fileXML.Save($writerXML)

마지막 줄이 없어진 것을 제외하고는 줄 끝이 바뀌는 것이 보이지 않습니다.그러나 BOM을 사용하면 ASCII에서 UTF8로 인코딩됩니다.

$a = get-content -raw file.xml
$a -replace '\r','r' -replace '\n','n'

<?xml version="1.0" encoding="utf-8"?>rn<Configuration>rn  <ViewDefinitions />rn</Configuration>rn

[xml]$b = get-content file.xml
$b.save('file.xml')

$a = get-content -raw file.xml
$a -replace '\r','r' -replace '\n','n'

<?xml version="1.0" encoding="utf-8"?>rn<Configuration>rn  <ViewDefinitions />rn</Configuration>

# https://gist.github.com/jpoehls/2406504
get-fileencoding file.xml

UTF8

언급URL : https://stackoverflow.com/questions/8160613/powershell-saving-xml-and-preserving-format