read the data from XML Structure using c#

▼魔方 西西 提交于 2019-12-25 02:21:31

问题


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


回答1:


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;



回答2:


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;



回答3:


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];
        }



回答4:


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




回答5:


Very close! Change it to this:

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

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



回答6:


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;




回答7:


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



来源:https://stackoverflow.com/questions/12838606/read-the-data-from-xml-structure-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!