Read only parts of an XML file

后端 未结 3 487
醉梦人生
醉梦人生 2021-01-29 14:31

 
  RadheyJang 
  India 
  Software Developer 
  

        
相关标签:
3条回答
  • 2021-01-29 14:40
        var ele = XElement.Parse(xml);
        // change to XElement.Load if loading from file  
        var result = ele.Descendants("Section").Zip(ele.Descendannt("Mark"),  (s,m) => new {Section = s.Value, Mark = m.Value}); Now you can create your DataTable:
    
        var table = new DataTable(); 
        var marks = new DataColumn("Mark");
        var sections = new     DataColumn("Sections"); 
        table.Columns.Add(marks); table.Columns.Add(sections); 
        foreach (var item in result) 
        {   
         var row = table.NewRow();   
         row["Mark"] = item.Mark;     
         row["Sections"] = item.Section; 
         table.Rows.Add(row);
        } 
    

    Try this Code ..

    0 讨论(0)
  • 2021-01-29 14:41

    You need to use XPath for this...

    using System.Xml.XPath;
    
    string xml = @"
        <Peoples>
            <People>
            <Name>RadheyJang</Name> 
            <Location>India</Location> 
            <Work>Software Developer</Work> 
            <Point>5</Point> 
            <details>
                <People>
                <Name>ArunaTiwari</Name> 
                <Location>India</Location> 
                <Work>SoFtwareCoder</Work> 
                <Point>3</Point> 
                <details/>
                <Test>A</Test>
                </People>
            </details>
            <Test>NA</Test>    
            </People>
        </Peoples>";
    
    XDocument xmlDoc = XDocument.Parse(xml);
    
    var vrresult = from a in xmlDoc.XPathSelectElements("/Peoples/People")
                    select new
                    {
                        Name = a.Element("Name").Value,
                        Location = a.Element("Location").Value,
                        Point = a.Element("Point").Value
                    };
    
    0 讨论(0)
  • 2021-01-29 14:51

    The only thing I can think of is that the XML is not legal:

    <Peoples>
     <People> *You have an opening People tag here*
      <Name>RadheyJang</Name> 
      <Location>India</Location> 
      <Work>Software Developer</Work> 
      <Point>5</Point> 
      <details> *You create a details tag here*
       <People> *You generate the same tag inside of another People tag*
        <Name>ArunaTiwari</Name> 
        <Location>India</Location> 
        <Work>SoFtwareCoder</Work> 
        <Point>3</Point> 
        <details/> *Then you close the details tag here*
        <Test>A</Test>
        </People>
      </details> *Then you close another one, but there is not a second opening detail tag*
      <Test>NA</Test>    
     </People>
    </Peoples>
    

    I'm not sure if this helps at all, but you might want to consider fixing up your XML.

    0 讨论(0)
提交回复
热议问题