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]

... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
13011정성태3/21/202215951오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/202212674오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/202215265개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/202214857VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/202213264.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/202215663.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/202213949오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/202213452디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/202213784.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/202215389.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/202215981.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/202214927.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/202214772.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/202213178.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202222286오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
12996정성태3/9/202223740VS.NET IDE: 175. Visual Studio - 인텔리센스에서 오버로드 메서드를 키보드로 선택하는 방법
12995정성태3/8/202216094.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
12994정성태3/8/202215167오류 유형: 798. WinDbg - Failed to load data access module, 0x80004002
12993정성태3/4/202214875.NET Framework: 1172. .NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
12992정성태3/3/202217833.NET Framework: 1171. C# - BouncyCastle을 사용한 암호화/복호화 예제파일 다운로드1
12991정성태3/2/202215637.NET Framework: 1170. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
12990정성태3/2/202215747오류 유형: 797. msbuild - The BaseOutputPath/OutputPath property is not set for project '[...].vcxproj'
12989정성태3/2/202213755오류 유형: 796. mstest.exe - System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.Tips.WebLoadTest.Tip
12988정성태3/2/202212163오류 유형: 795. CI 환경에서 Docker build 시 csproj의 Link 파일에 대한 빌드 오류
12987정성태3/1/202214435.NET Framework: 1169. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 demuxing_decoding.c 예제 포팅
12986정성태2/28/202216405.NET Framework: 1168. C# -IIncrementalGenerator를 적용한 Version 2 Source Generator 실습 [1]
... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...