V.V
V.V

Reputation: 883

read the data from XML Structure using c#

I store the xml file in one string object like,I stored the xml structure in local variable string abcd in c#.

 <structure>
    <a>Test Name</a>
    <e>test address</e>
    <c>
       <c1>yyyy<c1>
       <c2>xxxx</c2>
    </c>
    </structure>

How to read(parse) this xml string using c# and store the tag a,and tag c1 ,tag c2 values in local variable using c#.

i tried like

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(abcd);

        XmlElement element = (XmlElement)xmldoc.GetElementById("a");

but i get null value.how to read the values from xml structure and stored in local variable using c#?

Upvotes: 1

Views: 6531

Answers (7)

pathfinder
pathfinder

Reputation: 134

To use the XDocument class in the accepted answer, you need to add:

using System.Xml.Linq;

AND

*From solution explorer, locate "references"
*right click "Add reference"
*search Assembles (Ctrl E) for XML
*select the xml.ling item
*click the check box that appears on the left
*choose okay

Upvotes: -2

Riccardo
Riccardo

Reputation: 1520

If i understand you are trying to access every different tag in the xml document so you should use GetElementsByTagName instead of GetElementById. This returns a XmlNodeList object containing all nodes with that tag name and you can get the First as NodeList.Item(0).InnerXml;

Upvotes: 0

L.B
L.B

Reputation: 116168

Linq2Xml is much easier to use.

var xElem = XElement.Parse(abcd);
var a = xElem.Element("a").Value;
var c = xElem.Element("c").Element("c1").Value;

Upvotes: 3

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Very close! Change it to this:

XmlDocument xmldoc = new XmlDocument(); 
xmldoc.LoadXml(abcd); 

XmlElement element = xmldoc.Root.Element("a").Value;

Upvotes: 0

cuongle
cuongle

Reputation: 75316

You can use LINQ to XML:

 var xDoc = XDocument.Parse(xml);

 var a = xDoc.Descendants("a").First().Value;
 var c1 = xDoc.Descendants("c1").First().Value;
 var c2 = xDoc.Descendants("c2").First().Value;

Upvotes: 3

bjelleklang
bjelleklang

Reputation: 496

Have you had a look at LINQ to XML yet? If not, see the reference at http://msdn.microsoft.com/en-us/library/bb387098.aspx

Upvotes: 0

andy
andy

Reputation: 6079

string test = " <structure><a>Test Name</a><e>test address</e><c><c1>yyyy</c1><c2>xxxx</c2></c></structure>";

        DataSet dataSet = new DataSet();

        dataSet.ReadXml(new StringReader(test));
        DataTable dt11 = new DataTable();
        DataTable dt12 = new DataTable();
        //return single table inside of dataset
        if (dataSet.Tables.Count > 1)
        {
            dt11 = dataSet.Tables[0];
            dt12 = dataSet.Tables[1];
        }

Upvotes: 0

Related Questions