C#
C# XML다루기1) XML Element 추가 작성하기 (Write)
악마성
2021. 2. 24. 11:28
728x90
반응형
최초 생성된 xml
<!-- XMLFile1.xml -->
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<MemoLists>
</MemoLists>
우선 최초 xml을 저장하는 위치를 실행위치에 있도록 해놓았으므로,
경로 지정
private string _strXMLPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "XMLFile1.xml");
"쓰기" 버튼을 눌렀을 때 값이 입력 되도록 이벤트에 연결
/// <summary>
/// 쓰기 쓰기
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (_IsExistXML() == true)
{
WriteXML();
}
else
{
MessageBox.Show("경로에 XML 파일이 없습니다.");
}
}/// <summary>
/// 쓰기 쓰기
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (_IsExistXML() == true)
{
WriteXML();
}
else
{
MessageBox.Show("경로에 XML 파일이 없습니다.");
}
}
실제 xml 작성 Write 하는 코드
/// <summary>
/// XML 작성하기
/// </summary>
private void WriteXML()
{
var xDoc = XDocument.Load(_strXMLPath);
string idValue = Guid.NewGuid().ToString();
// ID Attribute의 값은 GUID 로 할 것.
xDoc.Root.Add(
new XElement("Memo",
new XElement("GUID", new XAttribute("value", idValue)),
new XElement("memo_title", "Untitle-01"),
new XElement("content", "아무내용")));
xDoc.Save(_strXMLPath);
}
참고로 위의 코드 실행 시 xml.ling를 사용했으므로 using 문에 넣어주어야 합니다.
using System.Xml;
using System.Xml.Linq;
최종 xml 결과물
728x90
반응형