안녕하세요.
매번 도움만 받고 있는 언제나 초보 개발자 입니다.
고객 요청사항이 아래처럼 XML 선언부가 나타나도록 하는 것인데,
<?xml version="1.0" ?>
XmlDocument와 XmlTextWriter를 이용해 파일을 쓰면, 항상 마지막 ? 앞에 공백이 없이 쓰여지고 있습니다.
<?xml version="1.0"?>
이 문제를 풀 수 있는 방법이 있을까요?
구글링 스킬이 부족한지 하루종일 뒤져봐도 답을 못 찾고 있습니다.
샘플 코드를 아래 추가합니다.
XmlDocument xDoc = new XmlDocument();
XmlElement xmlElement = xDoc.DocumentElement;
XmlDeclaration xmlDecl = xDoc.CreateXmlDeclaration("1.0", null, null);
xDoc.InsertBefore(xmlDecl, xmlElement);
XmlNode node = xDoc.CreateElement("Datas");
XmlNode childNode = xDoc.CreateElement("Data");
XmlAttribute attr = xDoc.CreateAttribute("ATTR1");
attr.Value = "Test1";
childNode.Attributes.Append(attr);
node.AppendChild(childNode);
childNode = xDoc.CreateElement("Data");
attr = xDoc.CreateAttribute("ATTR2");
attr.Value = "Test2";
childNode.Attributes.Append(attr);
node.AppendChild(childNode);
xDoc.AppendChild(node);
using (XmlTextWriter writer = new XmlTextWriter(@"D:\80.Test\Sample.xml", System.Text.Encoding.UTF8))
{
writer.Formatting = System.Xml.Formatting.Indented;
writer.Indentation = 4;
xDoc.WriteTo(writer);
writer.Flush();
}
먼저 감사 인사 드립니다.
2개의 좋아요
nyjin
2
이런 요구사항도 있네요.
2가지 방법이 있을 것 같습니다.
- 동작에 이슈가 없으니 말로 설명해서 풀어본다.
- xml 파일이 만들어진 다음, StringWriter로 파일을 다시 열어 xml 선언부를 강제로 재작성하여 다시 저장한다.
첫번째로 해결 되시길 바래요~
2개의 좋아요
Kuro78
3
조언 감사합니다~
Indent 숫자, 공백 개수 까지도 지정을 하고 있습니다. T^T
덕분에 XML 파싱에 대해 이런 저런 옵션들을 강제 습득하고 있지요…
첫 번째로 해결해 보려 했지만, 안되어 두 번째 방법으로 XML 내용을 String으로 받을 수 있는 방법을 찾아보고 있습니다.
2개의 좋아요
XMLDocument에서 xml선언부를 제거하고, 최종 코드를 아래와 같이 구현했습니다.
XmlDocument xDoc = new XmlDocument();
XmlNode node = xDoc.CreateElement("Datas");
XmlNode childNode = xDoc.CreateElement("Data");
XmlAttribute attr = xDoc.CreateAttribute("ATTR1");
attr.Value = "Test1";
childNode.Attributes.Append(attr);
node.AppendChild(childNode);
childNode = xDoc.CreateElement("Data");
attr = xDoc.CreateAttribute("ATTR2");
attr.Value = "Test2";
childNode.Attributes.Append(attr);
node.AppendChild(childNode);
xDoc.AppendChild(node);
using (var sw = new StringWriter())
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
xmlDoc.WriteTo(writer);
// xml 선언에서 version 뒤 공백(space) 추가를 지원하지 않아 직접 쓰는 방식으로 구현
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" ?>");
sb.Append(sw.ToString());
File.WriteAllText(@"D:\80.Test\Sample.xml", sb.ToString(), Encoding.UTF8);
}
3개의 좋아요