MichaelTaylor3D
MichaelTaylor3D

Reputation: 1665

Deserializing poorly structured XML without linq C#

I have an external xml feed that is pretty poorly structured so Im not sure how to deserialize it directly.

I can not use System.IO.Linq in my assembly so the only solution I know of cant be used.

Example of this xml is

<body>
    <route>
        <stop tag="Info I need to get"/>
        <stop tag="Info I need to get"/>
        <path>
            <point tag="info I need to get"/>
            <point tag="info I need to get"/>
            <point tag="info I need to get"/>
        </path>
        <path>
            <point tag="info I need to get"/>
        </path>
        <path>
            <point tag="info I need to get"/>
            <point tag="info I need to get"/>
        </path>
    </route>
</body>

if I could somehow parse all the path points into an array I can get the data inside the tags easily.

the linq solution I was refering to is mentioned at How to parse multiple single xml elements in .Net C#

Upvotes: 0

Views: 168

Answers (5)

Surya Pratap
Surya Pratap

Reputation: 495

Another way would be to use the xml reader XML Reader MSDN you can just look for elements of type path and load the attribute data using something similar to Reading Attributes

Upvotes: 0

L.B
L.B

Reputation: 116168

You can use XPath to select all nodes having tag attribute

XmlDocument doc = new XmlDocument();
doc.Load("myfile.xml");

foreach (XmlElement node in doc.SelectNodes("//*[@tag]"))
{
    Console.WriteLine(node.Name + ": " + node.GetAttribute("tag"));
}

Upvotes: 3

Carthorn
Carthorn

Reputation: 43

You could use an XmlSerializer :

Here is a good example: Simple XmlSerializer example

This would allow you to serialize the object for storage.

Upvotes: 0

CodingGorilla
CodingGorilla

Reputation: 19852

Can you use XmlDocument?

You might need to learn some XPath to be able to navigate it well, but this should do the trick.

You could also just do something simple like this:

XmlDocument doc = new XmlDocument();
doc.Load("myfile.xml");
foreach(XmlNode node in doc.SelectNodes("point"))
{
    var valueYouWant = node.Attributes["tag"].Value;
    // etc.
} 

Upvotes: 2

COLD TOLD
COLD TOLD

Reputation: 13599

I would recomend using array list since I would guess you do not now exact number of nodes

ArrayList list = new ArrayList();
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("point"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   list.Add(node);
}

Upvotes: 2

Related Questions