Nice programing

C #에서 XDocument를 사용하여 XML 파일 생성

nicepro 2020. 10. 11. 11:17
반응형

C #에서 XDocument를 사용하여 XML 파일 생성


List<string>포함 하는 "sampleList"가 있습니다.

Data1
Data2
Data3...

파일 구조는 다음과 같습니다.

<file>
   <name filename="sample"/>
   <date modified ="  "/>
   <info>
     <data value="Data1"/> 
     <data value="Data2"/>
     <data value="Data3"/>
   </info>
</file>

저는 현재 XmlDocument를 사용하여이 작업을 수행하고 있습니다.

예:

List<string> lst;
XmlDocument XD = new XmlDocument();
XmlElement root = XD.CreateElement("file");
XmlElement nm = XD.CreateElement("name");
nm.SetAttribute("filename", "Sample");
root.AppendChild(nm);
XmlElement date = XD.CreateElement("date");
date.SetAttribute("modified", DateTime.Now.ToString());
root.AppendChild(date);
XmlElement info = XD.CreateElement("info");
for (int i = 0; i < lst.Count; i++) 
{
    XmlElement da = XD.CreateElement("data");
    da.SetAttribute("value",lst[i]);
    info.AppendChild(da);
}
root.AppendChild(info);
XD.AppendChild(root);
XD.Save("Sample.xml");

XDocument를 사용하여 동일한 XML 구조를 어떻게 만들 수 있습니까?


LINQ to XML을 사용하면 다음 세 가지 기능을 통해이 작업을 훨씬 더 간단하게 할 수 있습니다.

  • 문서의 일부를 몰라도 객체를 구성 할 수 있습니다.
  • 개체를 생성하고 자식을 인수로 제공 할 수 있습니다.
  • 인수가 반복 가능한 경우 반복됩니다.

따라서 여기에서 다음을 수행 할 수 있습니다.

void Main()
{
    List<string> list = new List<string>
    {
        "Data1", "Data2", "Data3"
    };

    XDocument doc =
      new XDocument(
        new XElement("file",
          new XElement("name", new XAttribute("filename", "sample")),
          new XElement("date", new XAttribute("modified", DateTime.Now)),
          new XElement("info",
            list.Select(x => new XElement("data", new XAttribute("value", x)))
          )
        )
      );

    doc.Save("Sample.xml");
}

이 코드 레이아웃을 의도적으로 사용하여 코드 자체가 문서의 구조를 반영하도록했습니다.

텍스트 노드를 포함하는 요소를 원하는 경우 텍스트를 다른 생성자 인수로 전달하여 구성 할 수 있습니다.

// Constructs <element>text within element</element>
XElement element = new XElement("element", "text within element");

Using the .Save method means that the output will have a BOM, which not all applications will be happy with. If you do not want a BOM, and if you are not sure then I suggest that you don't, then pass the XDocument through a writer:

using (var writer = new XmlTextWriter(".\\your.xml", new UTF8Encoding(false)))
{
    doc.Save(writer);
}

참고URL : https://stackoverflow.com/questions/2948255/xml-file-creation-using-xdocument-in-c-sharp

반응형