XMl 파일을 로드하기전에 xml 파일을 선택하고 출력 디렉토리에 복사를 항상복사로 변경한다.
TestXml.cs
class TestXml
{
static void Main(string [] args)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("XMLFile1.xml");
XmlNode xNode = xdoc.SelectSingleNode("/Point");
if( xNode != null)
{
// 대소문자 구분하니 유의.
string x = xNode.Attributes["X"].Value;
string y = xNode.Attributes["Y"].Value;
Console.WriteLine($"({x} , {y})");
}
}
}
XMLFile1.xml
<?xml version="1.0" encoding="utf-8" ?>
<Point X="1" Y="2"/>
TestXml.cs
XmlDocument xdoc2 = new XmlDocument();
xdoc2.Load("XMLFile2.xml");
XmlNodeList xNode2 = xdoc2.SelectNodes("/StudentList/Student");
if(xNode2 != null)
{
foreach (XmlNode student in xNode2)
{
string name = student.Attributes["Name"].Value;
Console.WriteLine($"({name})");
}
}
XMLFile2.xml
<?xml version="1.0" encoding="utf-8" ?>
<StudentList>
<Student Name="강호동"/>
<Student Name="이수근"/>
<Student Name="이상민"/>
<Student Name="서장훈"/>
</StudentList>
XmlDocument를 활용하여 유럽통화기준 환율 가져오기
Money.cs
class MoneyRate
{
static void Main(string [] args)
{
// 유럽기준 환율 5.18일 날짜 뽑아오기
string Murl = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml?a0c493408b6984bda8cf20ccf4e21ac6";
XmlDocument xml = new XmlDocument();
xml.Load(Murl);
// namespace : xmlns
var nameS = new XmlNamespaceManager(xml.NameTable);
nameS.AddNamespace("ns", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
XmlNode xNode = xml.SelectSingleNode("//ns:Cube[@time='2020-05-18']",nameS); //접근할 노드
XmlNodeList xNodeList = xNode.SelectNodes("ns:Cube",nameS);
if (xNodeList != null)
{
foreach (XmlNode node in xNodeList)
{
Console.WriteLine($"{node.Attributes["currency"].Value} , 환율 : {node.Attributes["rate"].Value}");
//string currency = node.Attributes["currency"].Value;
//string rate = node.Attributes["rate"].Value;
//Console.WriteLine($"({currency} , 환율 : {rate})");
}
}
}
}
Book.xml 에서 데이터 파싱해오기
Book.xml
<?xml version="1.0" encoding="utf-8" ?>
<BookList>
<Book>
<Title>C#</Title>
<Author>임재민 저</Author>
<Publitsher>재민출판사</Publitsher>
</Book>
<Book>
<Title>java</Title>
<Author>다으리 저</Author>
<Publitsher>구앙출판사</Publitsher>
</Book>
</BookList>
BookXmlReader.cs
class BookXmlReader
{
public static void Main(string [] args)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("Book.xml");
XmlNodeList xnList = xDoc.SelectNodes("/BookList/Book");
foreach(XmlNode k in xnList)
{
Console.WriteLine($"제목: {k["Title"].InnerText}, 저자 : {k["Author"].InnerText} , 출판사 : {k["Publitsher"].InnerText}");
}
}
}
같은개념인데 이런식으로 하나하나씩 접근도 가능
foreach(XmlNode k2 in xnList)
{
string title = k2.SelectSingleNode("Title").InnerText;
string Author = k2.SelectSingleNode("Author").InnerText;
string Publitsher = k2.SelectSingleNode("Publitsher").InnerText;
Console.WriteLine($"제목:{title,-10}, 저자 : {Author,-10} , 출판사 : {Publitsher,-10}");
}
Book.xml을 nodeElement로도 접근할 수 있는듯.