Extract Data from XML using C#

This code will take data from InfoPath document (xml) and print it out. You will need to modify it for your needs.


//Import in the xml
bool flag = true; //to stop the while loop

//load xml file
StreamReader xmlStream = new StreamReader("doc.xml");
XmlDocument xmlDocument = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("dfs", "schema1");
nsmgr.AddNamespace("d", "schema1");
nsmgr.AddNamespace("xdado", "schema1");
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlReaderSettings xset = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
XmlReader rd = XmlReader.Create(xmlStream, xset, context);
xmlDocument.Load(rd);

//get the root
XmlNode root = xmlDocument.DocumentElement.FirstChild;

//get the first child
XmlNode child = root.FirstChild;

//get the child's sibling
child = root.NextSibling;

//get that child's first child
child = child.FirstChild;

//While we still have data
while (flag == true && child != null)
{
//get all the attributes of the child. This is all of the stuff in the quotes

XmlAttributeCollection attr = child.Attributes;
//loop through all child attribues and print them out.
for (int i = 0; i 0)
{
Console.WriteLine("keep going....");
child = child.FirstChild;
}
else
{
//child = child.NextSibling;
if (child.NextSibling != null)
{
child = child.NextSibling;
Console.WriteLine("keep going...");
}
else
{
XmlNode parent = child.ParentNode;
child = parent.NextSibling;
}
}
}

Here’s a simple pseudo code in case you are confused:


flag = true
load xml
get root
get child
get sibling
get child

if (true)
get child
get all attributes
if next child exists. go back to loop
else
get sibling
if sibling exist. go back to loop.
else
get parent. get sibling
if sibling exist go back to loop
else
flag = false;

Advertisement
This entry was posted in C#, QC and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s