XmlDocument 類別的使用

 

一、XmlDocument 類別的使用範例

using System.Xml;

string responseBody = @"
<bookstore xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
    <Book id='1' order='2'>
        <title>PC DIY</title>
        <author>pcman</author>
        <year>2000</year>
    </Book>
    <Book id='2' order='1'>
        <title>step by step to be programer</title>
        <author>Bill</author>
        <year>1997</year>
    </Book>
</bookstore>
";

XmlDocument doc = new XmlDocument();
doc.LoadXml(responseBody);

Console.WriteLine("用 XmlNode 來處理");
XmlNode? bookstore = doc.FirstChild;
Console.WriteLine(bookstore?.OuterXml);
Console.WriteLine();

string? firstOrder = bookstore?.FirstChild?.Attributes?.GetNamedItem("order")?.Value;
Console.WriteLine(firstOrder);
Console.WriteLine();

string? firstOrder22 = bookstore?.FirstChild?.Attributes?["order"]?.Value;
Console.WriteLine(firstOrder22);
Console.WriteLine();

string? firstBookTitle = bookstore?.SelectSingleNode("/bookstore/Book/title")?.InnerText;
Console.WriteLine(firstBookTitle);
Console.WriteLine();

foreach (XmlNode item in bookstore?.ChildNodes)
{
    Console.WriteLine(item["title"]?.InnerText);
}
Console.WriteLine();

//for (int i = 0; i < bookstore?.ChildNodes.Count; i++)
//{
//    Console.WriteLine(bookstore?.ChildNodes?[i]?["title"]?.InnerText);
//}

Console.WriteLine("用 XmlElement 來處理");
XmlElement? bookstore2 = doc.DocumentElement;
Console.WriteLine(bookstore2?.OuterXml);
Console.WriteLine();

string? firstOrder2 = bookstore2?.FirstChild?.Attributes?.GetNamedItem("order")?.Value;
Console.WriteLine(firstOrder2);
Console.WriteLine();

string? firstBookTitle2 = bookstore2?.SelectSingleNode("/bookstore/Book/title")?.InnerText;
Console.WriteLine(firstBookTitle2);
Console.WriteLine();

XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("xmlns-prefix", "");
XmlNodeList xmlNodeList = doc.SelectNodes("//xmlns-prefix:author", namespaceManager);
if (xmlNodeList.Count > 0)
{
    string pCpe2 = xmlNodeList[0].InnerText.ToLower();
    Console.WriteLine(pCpe2);
    Console.WriteLine();
}

foreach (XmlNode item in bookstore2?.ChildNodes)
{
    Console.WriteLine(item["title"]?.InnerText);
}

 

二、其他

1、XML屬性裡面的格式不能含有 & 符號,所以要將 & 取代成 &amp;。

2、DocumentElement 取得文件的根

3、innerXML與outerXML的差別是innerXML是顯示該節點但不包含最外層節點,outerXML是顯示該節點而包含最外層節點

4、有使用 SelectNodes 方法之 XPath 語法時,通常還需要搭配 XmlNamespaceManager 使用,這樣才能比對到資料。

 

參考資料:

.net core 雜記:WebAPI的XML請求和響應

XPath

XPath Examples

XML Schema Tutorial

web api xml 範例 HttpResponseMessage、HttpStatusCode 的使用