开发者

Reading an XML File and Selecting Nodes in .NET

I have a heavier XML file with lots and lots of tree nodes. I need to pick-up some particular node (for example say Diet), under which there are multiple sections.

ie. Diet node occurs randomly in the XML, so i need to find the node 开发者_C百科as Diet and get its child elements and save it to DB.

Assume that Diet is not only one line, it has 10-12 entries underneath it (may be i can get its contents using InnerXML, but really can't get line by line nodes)


  1. Make sure you have added a reference to "System.xml.Linq'.
  2. Suck out all the Diet elements:

    XElement wholeFile = XElement.Load(@"C:\DietSampleXML.xml");
    IEnumerable<XElement> dietElements = wholeFile.Descendants("Diet");
    
  3. If you set a breakpoint and hover the mouse over "dietElements" and click "Results View", you will see all the Diet elements and their inner xml.

  4. Now iterate through dietElements to add each element and/or children to your database: "foreach (XElement x in dietElements) { ... }"

I tested this with the following xml:

<?xml version="1.0" encoding="utf-8" ?>
<TestElement>
  <Diet>
    <Name>Atkins</Name>
    <Colories>1000</Colories>
  </Diet>
  <TestElement2>
    <Diet>
      <Name>Donuts Only</Name>
      <Calories>1500</Calories>
    </Diet>
  </TestElement2>
  <TestElement3>
    <TestElement4>
      <Diet>
        <Name>Vegetarian</Name>
        <Calories>500</Calories>
      </Diet>
    </TestElement4>
  </TestElement3>
</TestElement>


Depending on the structure of your XML file, you might try loading it into a DataSet (DataSet.ReadXML()) and see what DataTable it puts your Diet nodes into ... if it parses it ok then it is pretty simple to loop through the DataTable and get all your Diet node values.

I wrote a little toy app that opens XML like that, listing all the DataTables in a tree view then showing the table content in a grid. The VS project file for it is here or just an MSI to install it is here, if you want to see how a DataSet parses your XML file.


In XPath, it's just //Diet

To say more, I'd need to know more about your environment.

var doc = XDocument.Load("yourfile.xml");
var nodes = from d in doc.Desendants("Diet")
            select d;

foreach(var node in nodes)
{   // do stuff with node
}


The pseudo code below, contains the XPath statement that would get you all elements who have a 'Diet' as parent. Since it produces a XmlNodeList you can walk every node and save it to the DB. For performance i would consider consolidating what you want to save, and then save it, not per line (round trip for every entry is sub-optimal)

XmlNodeList list = xDoc.DocumentElement.SelectNodes("//*[parent::Diet]"); foreach (XmlNode entry in list) { DAL.SaveToDatabase(entry); }

Hope this helps,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜