开发者

Retrieve Some Data From Xml File

I have a question about reading xml. My xml format is like this:

<?xml version="1.0" encoding="utf-8"?>
<object type="System.Windows.Forms" name="Form1">
   <object>    
      <object type="label" name="lbl1">
         <prop>firstname</prop>
      </object>
   <dataset>
      <table name="tblOne">
         <data>
            <prop1>AA</prop1>
            <prop2>BB</prop2> 
         <data>     
     </table>
     <table name="tblTwo">
        <data>          
           <prop1>CC</prop1>        
        </data>
     </table>
   </dataset>
      <object>     
         <object type="textbox" name="txt1"&开发者_开发知识库gt;
          <prop>ABC</prop>  
     </object>
   <dataset>
      <table name="tblThree>
         <data>         
            <prop1>DD</prop1>
               <prop2>EE</prop2>        
         </data>
      </table>
   </dataSet>
</object>

I want to retrieve all data in tables Of dataset like this,

<prop1>AA</prop1>
<prop2>BB</prop2> 
<prop1>CC</prop1>
<prop1>DD</prop1>
<prop2>EE</prop2> 

And then i need to check these item is prop1 or prop2 and i will insert it to some table.i am using with c#. How do I read the xml?


To get the name/value pairs:

var root = XElement.Parse(xml);
var pairs = (from prop in root.Descendants("data").Elements()
             where prop.Name.LocalName.StartsWith("prop")
             select new { Name = prop.Name.LocalName, Value = (string)prop }
            ).ToList();

Then just iterate and add to whatever table you indend:

foreach(var pair in pairs) {
     // use pair.Name and pair.Value
}


I suggest you search google for c# xml.


You can use xpath. '//data' expression will return all data elements

XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // replace str with xml

XmlNodeList xnList = xml.SelectNodes("//data");

foreach (XmlNode xn in xnList)
{
   //Read <prop> nodes
}

XPath Examples

Manipulate XML data with XPath and XmlDocument (C#)


try this

var doc = XDocument.Parse(sourceText);
var result = doc.Descendants("data").Descendants();


This is hint ... It will works....

       protected void Page_Load(object sender, EventArgs e)
     {
        this.data1();
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("~/xyz.xml"));
        lblMsg.Text = ds.Tables[0].Rows[0]["data"].ToString();
    }

    private void data1()
    {

        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("~/xyz.xml"));
        int data = Int32.Parse(ds.Tables[0].Rows[0]["data"].ToString());
        hits += 1;
        ds.Tables[0].Rows[0]["data"] = data.ToString();
        ds.WriteXml(Server.MapPath("~/xyz.xml"));

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜