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
Solved

Reading from xml and populating xml file in a loop

Posted on 2006-06-30
7
248 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Hey!!!! 1 24
Winform Module - What is the ASP.Net equiv 2 28
Problem with SelectList in .NET MVC application 1 26
RegEx with optional part 4 42
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

808 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