Thursday, December 15, 2011

working with xml

Few days ago, I got a task to provide a Chart with with the chart highlights which is a brief description of the chart value. To get the chart is easier then to get the values of the chart. '
There are 3 links to get the values from. From the first xml file, I manage to find a way to get the value based on the node name.

Get nodes (and values) after selected node

Dictionary dict = new Dictionary();

private
void getElement(string URLString, string tagName)

{

XmlTextReader reader = new XmlTextReader(URLString);

reader.WhitespaceHandling = WhitespaceHandling.None;

XmlDocument doc = new XmlDocument();

doc.Load(reader);

if ((doc != null))

{

try

{

int i = 0;

XmlNodeList elemList = doc.GetElementsByTagName(tagName);

foreach (XmlNode elem in elemList)

{

for (int j = 0; j < elem.ChildNodes.Count; j++)

{

callChildNode(elem.ChildNodes[j]);

}

i++;

}

}

catch (Exception ex)

{

// exception

throw ex;

}

}

}

private void callChildNode(XmlNode node)

{

if (node.Name != "#text")

if (node.ChildNodes.Count == 1 )

dict.Add(node.Name, node.InnerText);

for (int j = 0; j < node.ChildNodes.Count; j++)

{

callChildNode(node.ChildNodes[j]);

}

}


From the line above, all the nodes with value after the tag that we defined will be listed inside the dictionary. That is for the case if you have a different xml tag that you wish to get the node value from (even if the node inside is the same with the node from the other tag).

------

Get node value based on another node's value

After the first XML, I thought everything is solved, but then when I saw the second XML, it was totally different from the first xml. Dang!! so I have to find a way to get value of a node based on another node's value.

I searched in the internet and got a sample of code from the link below:

http://stackoverflow.com/questions/6203666/xpath-select-a-node-based-on-another-node

Below are the code

var doc = new XmlDocument();
doc.
LoadXml(xmlString);
XmlElement element = (XmlElement)doc.SelectSingleNode("Items/Item[Code='MyCode']/Value");
Console.WriteLine(element.InnerText);


Hope this two code will be useful..

0 comments:

Post a Comment