Solved

Reading from xml and populating xml file in a loop

Posted on 2006-06-30
7
253 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
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 video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

707 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