c# 操作 xml

來源:互聯網
上載者:User

c# 操作 xml

在System.XMl 有以個類可以操作xml

(網上對這些類的記錄真得很少啊 可能因為類比較多吧  msdn的介紹)

 

建立一個新的xml

            XmlDocument xmldoc = new XmlDocument();
//在XML的文檔的最頭部加入XML的聲明段落
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmldoc.AppendChild(xmlnode);
//建立根節點
XmlElement root = xmldoc.CreateElement("root");
root.InnerText = "我是根節點";
xmldoc.AppendChild(root);

xmldoc.Save(@"D:\My Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\test.xml");

產生的xml是這樣的

<?xml version="1.0"?>  
<root>我是根節點</root>

 

另外一種建立建立xml的方法

            XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<root>我是根節點</root>"
);
xmldoc.Save(@"D:\My Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\test.xml");

讀取xml

xml如下

<?xml version="1.0" encoding="utf-8"?>
<root id="root">
<list num="0">
<name type="string">minglecun</name>
<age type="number">55</age>
</list>
<list num="1">
<name type="string">huluwa</name>
<age type="number">1</age>
</list>
</root>

 

            XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"D:\My Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\test.xml");
//讀某個節點
XmlNode xmlnode = xmldoc.SelectSingleNode("//root");
Console.WriteLine(xmlnode.InnerXml);
Console.WriteLine("------------------------------------------------");
XmlNode xmlnode1 = xmldoc.SelectSingleNode("//root//list");
Console.WriteLine(xmlnode1.InnerXml);
Console.WriteLine("------------------------------------------------");
//
XmlNodeList xn0 = xmldoc.SelectSingleNode("//root").ChildNodes;
foreach (XmlNode node in xn0)
{
Console.WriteLine("========"+node.Name);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.