這篇文章主要介紹C#中XML基礎用法有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
XML:可擴展標記語言。
純文本,兼容性強。
xml: 主要用來處理、存儲數據。無規定標簽,可擴展。
html:對數據的顯示和描述。 語法標簽固定。
區分大小寫。
只能有一個根節點。
標簽成對出現。
屬性用雙引號。
沒有預定標簽,用什么寫什么
文檔聲明:<?xml version=".." encoding="...">
注釋: <!-- -->
CDATA: 原意文本 <![CDATA[..] ] >
class Program
{
static void Main(string[] args)
{
//實現xml的寫入
//1、在內存中構建Dom對象
XmlDocument xmlDoc = new XmlDocument();
//增加文檔說明
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
xmlDoc.AppendChild(xmlDeclaration);
//增加根元素
// 創建根元素
XmlElement rootElement = xmlDoc.CreateElement("school");
xmlDoc.AppendChild(rootElement);
//3、增加子元素,接下來添加的子元素增加到rootElement節點下
XmlElement xmlClassElement = xmlDoc.CreateElement("class");
// 為class元素添加id屬性
XmlAttribute attr = xmlDoc.CreateAttribute("id");
attr.Value = "x01";
xmlClassElement.Attributes.Append(attr);
rootElement.AppendChild(xmlClassElement);
//4、為class創建student節點。
XmlElement xmlStudentElement = xmlDoc.CreateElement("student");
// 為student元素添加sid 屬性.
XmlAttribute studentAttr = xmlDoc.CreateAttribute("sid");
studentAttr.Value = "s011";
xmlStudentElement.Attributes.Append(studentAttr);
xmlClassElement.AppendChild(xmlStudentElement);
//student中增加name節點。
XmlElement xmlNameElement = xmlDoc.CreateElement("name");
xmlNameElement.InnerText = "天";
xmlStudentElement.AppendChild(xmlNameElement);
//2、將該Dom對象寫入xml文件中
xmlDoc.Save("school.xml");
Console.WriteLine("ok");
}
}以上方法可以用循環寫入。
class Program
{
static void Main(string[] args)
{
// 通過xdocument 寫入文件
List<Person> list = new List<Person>();
list.Add(new Person() { Name = "Sam", Age = 18 });
list.Add(new Person() { Name = "Penny", Age = 20 });
// 1、 創建Dom對象。
XDocument xDoc = new XDocument();
XDeclaration xDec = new XDeclaration("1.0", "utf-8", null);
// 設置文檔定義
xDoc.Declaration = xDec;
//2、創建根節點
XElement rootElement = new XElement("List");
xDoc.Add(rootElement);
//3、循環創建節點
for (int i = 0; i < list.Count; i++)
{
XElement PersonElement = new XElement("Person");
PersonElement.SetAttributeValue("id", (i + 1).ToString());
PersonElement.SetElementValue("Name", list[i].Name);
PersonElement.SetElementValue("Age", list[i].Age);
rootElement.Add(PersonElement);
}
xDoc.Save("List.xml");
Console.WriteLine("ok");
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}class Program
{
static void Main(string[] args)
{
//讀取XML文件。
XDocument document = XDocument.Load("List.xml");
XElement rootElement = document.Root;
Console.WriteLine("訂購人:{0}",rootElement.Element("CustomerName").Value);
foreach (var item in rootElement.Element("Items").Elements("OrderItem"))
{
Console.WriteLine("商品名稱:{0}",item.Attribute("Name").Value);
}
}
}以上是“C#中XML基礎用法有哪些”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。