smilu
smilu

Reputation: 899

How to read XML in C#?

I have an XML file which looks like this

<ss:demo>
<ss:Name>
    <ss:FirstName>First</ss:FirstName>
    <ss:SecondName>Second</ss:SecondName>
</ss:Name>
<ss:country code="IN">India</ss:country>
</ss:demo>

How can I read this using C#. Please help me in this. which will be easiest way for reading it? I tried to read it into a DataSet but its showing some error.

Upvotes: 1

Views: 345

Answers (2)

yamen
yamen

Reputation: 15618

How about just LINQ to XML?

Given this:

var xml = "<ss:demo>\r\n<ss:Name>\r\n    <ss:FirstName>First</ss:FirstName>\r\n    <ss:SecondName>" +
"Second</ss:SecondName>\r\n</ss:Name>\r\n<ss:country code=\"IN\">India</ss:country>\r\n</ss" +
":demo>";

(Note I had to wrap IN in quotes as such "IN")

Declare some namespaces and read it in:

var mngr = new XmlNamespaceManager( new NameTable() );
mngr.AddNamespace( "ss", "urn:ignore" ); // or proper URL
var parserContext = new XmlParserContext(null, mngr, null, XmlSpace.None, null);

If reading from a string as above:

var txtReader = new XmlTextReader( xml, XmlNodeType.Element, parserContext );

If reading from a file instead:

var txtReader = new XmlTextReader( new FileStream(filename, FileMode.Open), XmlNodeType.Element, parserContext );

Then load:

var ele = XElement.Load( txtReader );

ele contains everything you need.

Upvotes: 3

Eric J.
Eric J.

Reputation: 150108

There are several strategies to read an XML document, or parts thereof, using C#. If you are more specific about what you want to do with the XML document, the community can provide you with more specific guidance.

Here are some top choices:

Linq to XML

http://msdn.microsoft.com/en-us/library/bb387098.aspx

http://msdn.microsoft.com/en-us/library/bb387065.aspx

XDocument (part of the Linq to XML framework)

http://msdn.microsoft.com/en-us/library/bb387063.aspx

XmlDocument

http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx

XPath

http://msdn.microsoft.com/en-us/library/ms256471.aspx

Upvotes: 6

Related Questions