Phần này, chúng ta sẽ tìm hiểu cách thức hiển thị một tài liệu XML sử dụng C# như thế nào. Thông thường bạn sẽ cần hiển thị nó ra các control trong Winform, WPF hoặc ASP.NET . . .
Nhưng để đơn giản, chúng ta sẽ thực hiện các code mẫu trong giao diện console trước nhé.
Hiển Thị Một Tài Liệu XML Trong C#
Như thường lệ sẽ có các cách làm việc như sau:A. Sử Dụng XmlDocument
- Ta có 2 phương thức phổ biến là lấy ra toàn bộ nội dung xml hoặc toàn bộ phần Text có trong xml. Phần text nằm giữa các thẻ tag của bạn.XmlDocument doc = new XmlDocument();
doc.Load("Test.xml");
string s = doc.InnerXml; // Lấy ra toàn bộ nội dung trong file tài liệu xml
string s1 =doc.InnerText; //Lấy ra chỉ dữ liệu không bao gồm các Attributes
-Để xem nội dung bên trong của một phần tử xác định có phương thức GetElementsByTagName như sau:
XmlDocument doc = new XmlDocment();- Để lấy giá trị attribute ta làm như sau:
doc.Load("TestNew.xml");
XmlNodeList list = doc.GetElementsByTagName("Node");
for(int i=0; i < list.Count; i++)
{
Console.WriteLine(list[i].InnerText);
}
XmlNodeList list = doc.GetElementsByTagName("Node");
for(int i=0; i < list.Count; i++)
{
Console.WriteLine(list[i].Attributes["ID"].Value);
}
B. Sử Dụng XDocument và Linq
Với dữ lieu mẫu như sau:<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?xml-stylesheet href='stenw.css' title='STENW' type='text/css'?>
<!--Your comment here....-->
<Root>
<Node ID="100">
<Name>Tuan Le Minh</Name>
<Country>Viet Nam</Country>
</Node>
<Node ID="101">
<Name>Tuan Le Minh</Name>
<Country>Viet Nam</Country>
</Node>
<Node ID="102">
<Name>Tuan Le Minh</Name>
<Country>Viet Nam</Country>
</Node>
<Node ID="103">
<Name>Tuan Le Minh</Name>
<Country>Viet Nam</Country>
</Node>
</Root>
- Để tải lên dữ liệu và xem nội dung của nó ta sử dụng các cách sau:
var doc = XDocument.Load("TestNew.xml");
var node = doc.Descendants("Node");
foreach (var e in node)
{
Console.WriteLine(e.Attribute("ID").Value
+ e.Element("Name").Value
+ e.Element("Country").Value);
}
Cách trên giúp bạn truy xuất được các phần tử bên trong phần tử "Node"
- Để xem toàn bộ tài liệu bao gồm các thẻ tag:
// Show document
var doc = XDocument.Load("TestNew.xml");
Console.WriteLine(doc.Document);
(to be continued)
Created: 26/04/2014
[XML] How To: Display XML Document In C#
Related Tags :WritingObsolete
No comments:
Post a Comment
Commets Download Photoshop Actions, Lightroom Presets, PSD Template, Mockups, Stocks, Vectors, Fonts. Download free