Solved

Reading from xml and populating xml file in a loop

Posted on 2006-06-30
7
241 Views
Last Modified: 2012-06-21
I have this xml

<TrackingHistory>
<Status sequence_nbr="3" final_delivery="true" usps="true"><Disposition>TU</Disposition>
<StatusDesc id="109">Final Delivery Confirmed.</StatusDesc>
<Date>2001-06-05</Date>
<Time>08:24</Time>
</Status>
<Status sequence_nbr="2"><Disposition>IB</Disposition>
<StatusDesc id="100">Arrived at DHL facility.</StatusDesc>
<Date>2001-06-04</Date>
<Time>05:39</Time>
<StatusLocation><![CDATA[RUNNENMEDE, NJ]]></StatusLocation>
<Location abf_station_id="NJS"><City>RUNNENMEDE</City>
<State>NJ</State>
<Country><![CDATA[UNITED STATES]]></Country>
</Location>
<EntryStation>NJS</EntryStation>
</Status>
<Status sequence_nbr="1"><Disposition>TU</Disposition>
<StatusDesc id="121">Transit through sort facility.</StatusDesc>
<Date>2001-06-02</Date>
<Time>05:05</Time>
<StatusLocation><![CDATA[WILMINGTON, OH]]></StatusLocation>
<Location abf_station_id="ILN"><City>WILMINGTON</City>
<State>OH</State>
<Country><![CDATA[UNITED STATES]]></Country>
</Location>
<EntryStation>ILN</EntryStation>
</Status>
</TrackingHistory>


I want to read 1)TrackingHistory/StatusDesc
            2)TrackingHistory/StatusDesc/Location/City
            3)TrackingHistory/StatusDesc/Location/State                  

in a loop and wants to populate one more xml file in a loop which is below.

<root>
<History>
<StatusDesc></StatusDesc>
<City></City>
<State></State>
</History>
</root>

which should form
<root>
<History>
<StatusDesc>xxx</StatusDesc>
<City>ccc</City>
<State>sss</State>
</History>
<History>
<StatusDesc>yyy</StatusDesc>
<City>ccc</City>
<State>ddd</State>
</History>
</root>

Could anybody help with sample code.





0
Comment
Question by:r_pat72
  • 2
7 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 17021027
You could try something like:

            XmlDocument source = new XmlDocument();
            source.Load("Your source XML file");

            XmlDocument target = new XmlDocument();
            target.LoadXml("<root />");

            XmlNodeList statuses = source.SelectNodes("//Status[StatusDesc]");

            foreach (XmlNode child in statuses)
            {
                XmlNode history = target.DocumentElement.AppendChild(target.CreateElement("History"));
                XmlNode temp = history.AppendChild(target.CreateElement("StatusDesc"));
                temp.InnerText = child["StatusDesc"].InnerText;

                if (child["Location"] != null)
                {
                    if (child["Location"]["City"] != null)
                    {
                        temp = history.AppendChild(target.CreateElement("City"));
                        temp.InnerText = child["Location"]["City"].InnerText;
                    }

                    if (child["Location"]["State"] != null)
                    {
                        temp = history.AppendChild(target.CreateElement("State"));
                        temp.InnerText = child["Location"]["State"].InnerText;
                    }
                }
            }

            target.Save("Your save path");


Note that this code takes into account that your source XML has some "Status" nodes that don't have a child "Location" node.
0
 
LVL 4

Expert Comment

by:Jigit
ID: 17026532
The above solution seems to be correct, but, I think, there are other better ways to perform it:
1. The best way is to create an XSL that will transforms your source XML into the target one. You can define such XSL only once and transform it easily from your C# code.
2. If you intend to perform this task only in C# code, please consider using task specific XML classes instead of XmlDocument. XmlDocument is the most powerful and richest class in XML, as it allows reading from the XML, searching inside of it, adding nodes etc. It's better using other classes for example for writing an XML XmlTextWriter.

Please specify what is the preffered way, and I wil try to help you with coding.

HTH,
Jigit
0
 

Author Comment

by:r_pat72
ID: 17027154
Jigit, xmldocument method will be fine. Could u provide some sample code.
0
 
LVL 4

Expert Comment

by:Jigit
ID: 17032719
carl_tawn already provided a working sample code using XmlDocument. I tried to explain why it's not recommended using XmlDocument class although it the most powerfull and it works: it uses much more resources and more time consuming than other "tasks specific classes", for example using XmlReader when you need only to read from XML or XmlTextWriter when you need only to write XML.

I personally prefer another technique: transforming a source XML into target XML using XSL. You can find sample code at:
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

HTH,
Jigit
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Why don't I see this table in EDMX file? 2 23
Name space syntax error 12 39
Error when loading the database 16 54
how to read json value 2 29
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now