开发者

xml parsing in C#

开发者 https://www.devze.com 2023-01-23 14:38 出处:网络
Hi Guys I would like to parse the following xml string in C# i tried reading the entire string into the dataset and then using it .. there are simply no tables in the dataset.

Hi Guys I would like to parse the following xml string in C# i tried reading the entire string into the dataset and then using it .. there are simply no tables in the dataset.

here is the开发者_运维百科 xml that I am interested to parse.

xml code is here http://pastebin.com/VfT2wAwY

C# code is here http://pastebin.com/iwqDK2S6


Thanks and regards, Gagan Janjua


Have you considered LINQ to XML? If you're using .NET Framework 3.5 or later, then LINQ can save you a lot of time.

I haven't tested this, but you could do something like:

XDocument doc = XDocument.Load(@"C:\mydocument.xml");

var allCases = doc.Element("response").Element("cases").Descendants("case");

foreach (var currentCase in allCases) {
    // I can now access each case specifically
    var allEvents = currentCase.Descendants("events");

    foreach (var currentEvent in allEvents) {
        // now I can access each event
        int ixBugEvent = (int)currentEvent.Element("ixBugEvent");
        // etc...
    }
}


Are you aware of XmlReader from System.Xml?

There is no schema in XML that you have provided, so you cannot expect that you can use it to populate DataSet... Unless you define your own schema, that is.


Your code is returning null because of your catch is making it null. It hits the catch, with the following error:

Column name 'ixBugEvent' is defined for different mapping types.

I have the impression that the reason for it is that you have ixBugEvent as both an attribute and a element

<event ixBugEvent='3' ixBug='2'>
          <ixBugEvent>3</ixBugEvent>

Removing one of them fix the issue. The code is working, but your xml schema cannot be translated to a dataset.


You can change Scott's code to make it work by changing the following line of code:

   // I can now access each case specifically
    var allEvents = currentCase.Descendants("events");

Make it:

   // I can now access each case specifically
    var allEvents = currentCase.Descendants("event");

Doing that you have access to each event element. And from there you can definitely have access to ixBugEvent element.

I hope this helps.

P.s.: Sorry to make this another answer, but I would like to highlight the code, and it seems the only way to do it...

0

精彩评论

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

关注公众号