Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

원본 파일의 공백/라인을 유지한 체 XML 파일을 저장하는 방법

아는 분과 이야기를 하다가, 그분은 XML 파일로 설정 저장을 하는 것이 싫어서 "Key=Value" 형식의 포맷으로 저장하는 간단한 라이브러리를 사용한다고 하십니다. ^^ XML이 싫은 이유인 즉, 저장하면서 기존 파일에 있던 공백/라인 형식이 모두 제거되고 다시 정렬되기 때문이라고 했습니다.

아하~~~ 아직도 모르고 계셨군요. ^^




예를 들어, 다음과 같은 문서를 로드한 경우,

<?xml version="1.0" encoding="utf-8" ?>

<configure>

    <myParam>1</myParam>

</configure>

XmlDocument로 Load/Save를 하면 기본적으로는 다음과 같이 저장됩니다.

<?xml version="1.0" encoding="utf-8"?>
<configure>
  <myParam>5</myParam>
</configure>

사용자가 멋있게(?) 포맷팅해 둔 텍스트 파일의 형식이 날아가 버린 것입니다. 이를 방지하려면 다음과 같이 Load 이전에 PreserveWhitespace = true 설정을 해주시면 됩니다.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("test.xml");

이렇게 로드된 파일을 저장하면 다음과 같이 서식(?)이 유지된답니다. ^^

<?xml version="1.0" encoding="utf-8" ?>

<configure>

    <myParam>5</myParam>

</configure>

재미있는 것은 PreserveWhitespace가 Load 이전에 설정했을 때와 Save 이전에 설정했을 때가 동작 방식이 다르다는 점입니다.

XmlDocument.PreserveWhitespace Property 
; https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.preservewhitespace

If PreserveWhitespace is true before Save is called, white space in the document is preserved in the output; otherwise, if this property is false, XmlDocument auto-indents the output.


더욱 재미있는 점은, 위의 문서 내용과는 다르게 다음과 같이 Save 이전에 값을 true로 설정해 주면 아예 공백 문자들이 모두 날아간 최적화된(?) 문자열을 반환한다는 것입니다.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("test.xml");

xmlDoc.PreserveWhitespace = true;
xmlDoc.Save(Console.Out);

// 출력 결과:
<?xml version="1.0" encoding="utf-8"?><configure><myParam>5</myParam></configure>

이렇게 해서 공백을 아예 제거하는 방법과, 사용자의 원본 서식을 유지하는 방법을 알아봤는데요. 그렇다면 '들여쓰기'를 정규화시켜서 출력을 해주고 싶다면 어떻게 해야 할까요? 그럴 때는 다음과 같이 XmlWriterSettings 옵션을 사용하시면 됩니다. ^^

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "    "; //  4개의 공백 문자
settings.NewLineChars = Environment.NewLine;
settings.NewLineHandling = NewLineHandling.Replace;

XmlWriter writer = XmlWriter.Create(Console.Out, settings);
xmlDoc.Save(writer);

그럼, 출력 결과는 다음과 같이 네모반듯(?)하게 나옵니다. ^^

<?xml version="1.0" encoding="ks_c_5601-1987"?>
<configure>
    <myParam>5</myParam>
</configure>

이 정도 자유롭게 출력할 수 있으니... XML 사용에 주저하지 마시길 바랍니다. ^^

(첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/17/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2012-03-06 01시04분
[지송] 좋은 팁 얻어갑니다. 따뜻한 봄 맞이하세요.
[guest]

... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11274정성태8/22/201719392.NET Framework: 674. Thread 타입의 Suspend/Resume/Join 사용 관련 예외 처리
11273정성태8/22/201721634오류 유형: 415. 윈도우 업데이트 에러 Error 0x80070643
11272정성태8/21/201724804VS.NET IDE: 120. 비주얼 스튜디오 2017 버전 15.3.1 - C# 7.1 공개 [2]
11271정성태8/19/201719264VS.NET IDE: 119. Visual Studio 2017에서 .NET Core 2.0 프로젝트 환경 구성하는 방법
11270정성태8/17/201730725.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기 [2]
11269정성태8/17/201721495디버깅 기술: 93. windbg - 풀 덤프에서 .NET 스레드의 상태를 알아내는 방법
11268정성태8/14/201721083디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
11267정성태8/10/201725140.NET Framework: 672. 모노 개발 환경
11266정성태8/10/201724946.NET Framework: 671. C# 6.0 이상의 소스 코드를 Visual Studio 설치 없이 명령행에서 컴파일하는 방법
11265정성태8/10/201753189기타: 66. 도서: 시작하세요! C# 7.1 프로그래밍: 기본 문법부터 실전 예제까지 [11]
11264정성태8/9/201724118오류 유형: 414. UWP app을 signtool.exe로 서명 시 0x8007000b 오류 발생
11263정성태8/9/201719602오류 유형: 413. The C# project "..." is targeting ".NETFramework, Version=v4.0", which is not installed on this machine. [3]
11262정성태8/5/201718257오류 유형: 412. windbg - SOS does not support the current target architecture. [3]
11261정성태8/4/201720835디버깅 기술: 91. windbg - 풀 덤프 파일로부터 강력한 이름의 어셈블리 추출 후 사용하는 방법
11260정성태8/3/201718953.NET Framework: 670. C# - 실행 파일로부터 공개키를 추출하는 방법
11259정성태8/2/201718190.NET Framework: 669. 지연 서명된 어셈블리를 sn.exe -Vr 등록 없이 사용하는 방법
11258정성태8/1/201719024.NET Framework: 668. 지연 서명된 DLL과 서명된 DLL의 차이점파일 다운로드1
11257정성태7/31/201719175.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201720664디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201723217디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201719594개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201719951Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201718462오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201717168디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201720725디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201718549오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...