将 XML 文件读入 XmlDocument

我是 C # 的新手。我有 XML 文件(text.XML)。我想在 XmlDocument中读取它,并将流存储在字符串变量中。

308610 次浏览

Use XmlDocument.Load() method to load XML from your file. Then use XmlDocument.InnerXml property to get XML string.

XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;

Hope you dont mind Xml.Linq and .net3.5+

XElement ele = XElement.Load("text.xml");
String aXmlString = ele.toString(SaveOptions.DisableFormatting);

Depending on what you are interested in, you can probably skip the whole 'string' var part and just use XLinq objects

If your .NET version is newer than 3.0 you can try using System.Xml.Linq.XDocument instead of XmlDocument. It is easier to process data with XDocument.

XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");


XmlNode node = doc.SelectSingleNode("Magasin");


XmlNodeList prop = node.SelectNodes("Items");


foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
var doc = new XmlDocument();
doc.Loadxml(@"c:\abc.xml");