Xml 구조 읽는 방법 예제
using System;
using System.Xml;
class Test
{
static void Main()
{
string testData =
"<main>" +
" <sub attribute1=\"SubAttribute\">" +
" <field name=\"first\">1</field>" +
" <field name=\"second\">" +
" <test>" +
" 2" +
" </test>" +
" </field>" +
" </sub>" +
"</main>";
XmlDocument xml = new XmlDocument();
//파일 경로로 읽는 방식
//xml.Load("파일 경로");
//string 읽는 방식
xml.LoadXml(testData);
//<sub> 가져오기
XmlNode subNode = xml.SelectSingleNode("main/sub"); //첫 번째 노드 가져옴
//<sub> attribute1 가져오기
string attribute1 = subNode.Attributes["attribute1"]?.Value;
Console.WriteLine($"attribute1 : {attribute1}");
//<sub><field> 가져오기
XmlNodeList fieldList = subNode.SelectNodes("field"); //Node의 Node 방식
//<field> 값들 순회
foreach (XmlNode node in fieldList)
{
string innterText = node.InnerText; //순수 값.
string innerXml = node.InnerXml; //xml 값 전체
Console.WriteLine($"innerText: {innterText}, innerXml: {innerXml}");
}
//번외) 항상 첫 번째 값을 가져옴 (field가 여러개)
string x = subNode["field"].Attributes["name"]?.Value; //"first"
Console.WriteLine($"first node : {x}");
}
}
'C# > Console' 카테고리의 다른 글
[C# Console] Base64 직접 만들어보기 (Convert.ToBase64String, Convert.FromBase64String) (0) | 2025.04.11 |
---|---|
[C# Console] AES256 사용 (+ 자바) (0) | 2025.04.02 |
[C#] 프로세스 실행 및 대기 (Process.Start , Process.WaitForExit) (0) | 2024.01.30 |
[C#] 금액 (숫자) -> 한글 (원)로 변환하기 (0) | 2023.01.23 |
[C#] StructLayout : 클래스/구조체 크기 설정 (0) | 2022.08.03 |