1

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#?

7 Answers 7

3

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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;

2 Comments

from string not from XML file
still a yummy answer though
0
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];
        }

Comments

0

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

Comments

0

Very close! Change it to this:

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

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

Comments

0

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;

Comments

-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.