I am very new to C#. I have XML file (text.xml). I want to read that in XmlDocument and store the stream in string variable.
Asked
Active
Viewed 3e+01k times
108
Limon Monte
- 48,600
- 44
- 172
- 205
AJP
- 2,075
- 3
- 16
- 22
-
1thank you both for your help. – AJP Feb 01 '12 at 23:52
5 Answers
181
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;
bluish
- 24,718
- 26
- 114
- 174
Timur Sadykov
- 10,211
- 6
- 31
- 43
-
2
-
I downvoted all of these because none of them worked. As it turns out, I am developing for WindowsRT, and the *Compact .NET Framework* has a lot of these features stripped out. Including a lot of the ones that I need... Such as `XmlDocument.Load()` and and the StreamReader constructor `StreamReader(filePath)` – Matt Clark Nov 12 '13 at 02:14
-
14@MattClark: I feel your pain - I've been struggling with the vagaries and limitations of CF for two years now - but that's no reason to downvote. The OP did not specify CF, and so there's no reason the answerers would take CF into consideration. – B. Clay Shannon-B. Crow Raven Jan 06 '15 at 22:56
18
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.
-
4And here's how to load a file using XDocument: http://stackoverflow.com/questions/670563/linq-to-read-xml – Brian Leeming Sep 04 '13 at 20:44
7
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);
}
Rahil Wazir
- 9,801
- 11
- 41
- 63
user3626085
- 71
- 1
- 1
6
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
Abdul Hfuda
- 1,453
- 12
- 24
0
var doc = new XmlDocument();
doc.Loadxml(@"c:\abc.xml");
Juliano Sales
- 1,001
- 1
- 7
- 12
-
-
3`XmlDocument.LoadXml()` loads an XML string. To load an XML file by name, use `XmlDocument.Load()` as the accepted answer suggests. – François Beaune Jan 27 '16 at 14:42