Solved

Reading from xml and populating xml file in a loop

Posted on 2006-06-30
7
238 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
Comment Utility
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
Comment Utility
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
Comment Utility
Jigit, xmldocument method will be fine. Could u provide some sample code.
0
 
LVL 4

Expert Comment

by:Jigit
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video discusses moving either the default database or any database to a new volume.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

772 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

11 Experts available now in Live!

Get 1:1 Help Now