Question

How to read xml document using C#?

Asked by: tryokane

I need to read an xml document.The xml document is in the format below.Can anyone tell me how to do?Code is appreciated.

<?xml version="1.0" standalone="yes" ?> 
- <PatientBill>
  <Header BillId="Simon Test" BillSubmitDate="2008-07-02" BillSubmitTime="18:06:41Z" /> 
- <Items>
  <Item d5p1:type="Episode" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" ItemType="EPISODE" EpisodeId="1" EpisodeDate="2008-07-02" EpisodeTime="18:06:41Z" AdmissionBedCode="B01" AdmissionWard="WD001" /> 
- <Item d5p1:type="IPMovement" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" IPMovementId="86894" DestinationLocation="QuantaTech Holdings Inc." TransferStartDate="1939-01-17" TransferStartTime="17:04:56Z" TransferToBed="T76" TransferToWard="R1478" TransferToBedType="E5" TransferToRoomType="D8" TransferEndDate="1927-01-21" TransferEndTime="16:09:14Z">
  <ItemType>IPMOVE</ItemType> 
  </Item>
- <Item d5p1:type="IPMovement" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" IPMovementId="14818" DestinationLocation="YoyoMatix Associates" TransferStartDate="1929-04-17" TransferStartTime="10:30:58Z" TransferToBed="K42" TransferToWard="P6637" TransferToBedType="I4" TransferToRoomType="R4" TransferEndDate="1948-05-31" TransferEndTime="07:36:35Z">
  <ItemType>IPMOVE</ItemType> 
  </Item>
- <Item d5p1:type="IPMovement" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" IPMovementId="56550" DestinationLocation="SynerSys Gmbh." TransferStartDate="1960-03-12" TransferStartTime="07:23:59Z" TransferToBed="G93" TransferToWard="O1409" TransferToBedType="O2" TransferToRoomType="P8" TransferEndDate="1950-02-24" TransferEndTime="05:58:56Z">
  <ItemType>IPMOVE</ItemType> 
  </Item>
- <Item d5p1:type="IPTheatreAnaesthetic" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" TheatreId="1" ChargeCode="Y61" OperationStatus="K6" AnaestheticMethod="X2996" AnaestheticStatus="W3" AnaestheticAgent="T5282" StartDate="34398" StartTime="2095" FinishDate="45557" FinishTime="2547">
  <ItemType>IPTHAN</ItemType> 
  </Item>
- <Item d5p1:type="IPTheatreAnaesthetic" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" TheatreId="1" ChargeCode="N62" OperationStatus="S5" AnaestheticMethod="N4431" AnaestheticStatus="R7" AnaestheticAgent="I1918" StartDate="44721" StartTime="4604" FinishDate="30953" FinishTime="2185">
  <ItemType>IPTHAN</ItemType> 
  </Item>
- <Item d5p1:type="IPTheatre" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" TheatreId="1" Procedure="H8193" TableCode="Q30" Priority="A57" TheatreInDate="1934-06-15" TheatreInTime="00:47:36Z" TheatreOutDate="1978-07-03" TheatreOutTime="00:37:59Z" OperationStatus="O53" PACUStartDate="1955-08-22" PACUStartTime="00:43:44Z" PACUReadyToLeaveDate="1985-01-06" PACUReadyToLeaveTime="01:14:42Z" AnaestheticStatus="E98">
  <ItemType>IPTHTR</ItemType> 
  </Item>
- <Item d5p1:type="IPTheatre" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" TheatreId="1" Procedure="E4628" TableCode="X19" Priority="G36" TheatreInDate="1926-04-08" TheatreInTime="01:04:47Z" TheatreOutDate="1961-06-23" TheatreOutTime="01:26:59Z" OperationStatus="R54" PACUStartDate="1969-07-18" PACUStartTime="00:17:23Z" PACUReadyToLeaveDate="1985-01-14" PACUReadyToLeaveTime="01:21:26Z" AnaestheticStatus="K59">
  <ItemType>IPTHTR</ItemType> 
  </Item>
- <Item d5p1:type="OrderItem" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" OrderItemId="111000" OrderItemCode="58599,1,1" BillingGroupCode="PHARMACY" BillingSubGroupCode="PHARMACY" OrderCategory="GENERAL PHARMACY" OrderSubCategory="CARBOHYDRATES" OrderSet="ORDER SET 1" StartDate="2008-07-03" StartTime="01:06:41Z" EndDate="2008-07-03" EndTime="01:06:00Z" Quantity="1" OIOrderingLocation="O1409" BillingStatus="TB" OIReceivingLocation="O1409" ListPrice="010" ItemPrice="009" ManualPriceOverride="009" DiscountedAmount="001" PharmacyClassification="XXX" ServiceTaxCode="EX">
  <ItemType>ORDITEM</ItemType> 
  </Item>
- <Item d5p1:type="OrderItem" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" OrderItemId="123421" OrderItemCode="CC20" BillingGroupCode="CONSULTATION" BillingSubGroupCode="OP CONSULTATION" OrderCategory="APPOINTMENT" OrderSubCategory="CONSULTATION" BillingStatus="TB" OIReceivingLocation="GP CLINIC" ListPrice="3000" ItemPrice="3000" Location="GP CLINIC" ApptID="1234565" ApptDate="2008-07-23" ApptTime="08:00:00Z" ApptStatus="DONE" ArrivalDate="2008-07-23" ArrivalTime="08:00:00Z" DepartureDate="2008-07-23" DepartureTime="09:00:00Z" CareProvider="0091" CareProviderType="GP" ServiceRendered="NNN" ServiceTaxCode="EX">
  <ItemType>ORDITEM</ItemType> 
  </Item>
  </Items>
  </PatientBill>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-07-24 at 21:27:41ID23594544
Topics

Extensible Markup Language (XML)

,

Microsoft Visual C#.Net

Participating Experts
2
Points
250
Comments
30

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. XML Documents
    Hi there I can parse an existing XML document using the TXMLDocument component that ships with Delphi but I've got trouble creating a new document using the component. I've tried createnode / and addnode but then most of the properties and methods are grayed out. Please he...
  2. Creating Dynamic XML documents
    New to this, but I want to create XML documents some how, but they need to be dynamic... the content is coming from other XML pages, I just want to create one instead of 4 or 5 different connections to seperate XML feeds... I was (prior to this excursion on a new solution) c...
  3. Consume XML Document
    I am writing an app to send and receive SMS over the internet using a SOAP COM object. I can send SMS but not receive the reply. Here is an extract from the COM Objet manual 3.1.14 GetUserOSReplies Method String GetUserOSReplies(String Token); Description: This function...
  4. XML document.
    Hi, I'm generating an XML document from a C++ program, all elements are being added correctly except for the 1st line : <?xmlversion="1.0"encoding="UTF-8"?> It just doesn't add it + it generates an error message. here's my code : out << &qu...
  5. xml documentation
    I have all of my code documented using xml documentation style.. I've compiled it all and I've gotten a nice xml file. Question is now what is the best way to display it on a webpage? or to display it at all. Is there an xsl stylesheet already out there somewhere? Do I have ...
  6. Looping through an XML document
    I have an XML document similar to the one below that I need to process and display in a windows fomm using a combination of tree-view and list view controls in C#. The element <Company> is the only one that I can guarantee will come in the same standard format each tim...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: naspinskiPosted on 2008-07-24 at 21:52:16ID: 22086062

It really depends on what you want to do with it, 'read it' is very vague.

For example, the following will return a list of all the 'ItemType' elements

XElement x = XElement.Load("filename.xml");
var listItemTypes = from elem in x.Descendants("ItemType") select elem;
 
//this is using .net 3.5 (linq)

                                              
1:
2:
3:
4:

Select allOpen in new window

 

by: lakshmidurgaPosted on 2008-07-24 at 22:09:38ID: 22086117


There are number of methods  to read an xml file-
go through these links-
http://www.vbdotnetheaven.com/UploadFile/mahesh/ReadXMLinVbDotNet04222005023510AM/ReadXMLinVbDotNet.aspx
http://www.vbdotnetheaven.com/UploadFile/bulentozkir/XMLfileUsingXmlDocument04232005010454AM/XMLfileUsingXmlDocument.aspx

You can also read xml file using dataset

dim ds as new dataset
ds.readxml("filename.xml")
do what ever you want.
But,if you want to do a specific task using this xml file,give a clear description of ur task.

 

by: lakshmidurgaPosted on 2008-07-24 at 22:11:00ID: 22086122

 

by: tryokanePosted on 2008-07-24 at 22:29:10ID: 22086162

I want to read each attribute value in the above xml file.Under Header i want to read all attributes.Similarly under item  i want all the attributes.How can i do this?I tried but didnt get.

 

by: naspinskiPosted on 2008-07-24 at 22:51:02ID: 22086221

.net 3.5 solution with Linq

XElement x = XElement.Load(Server.MapPath(".") + "\\App_Data\\PatientBill.xml");//path to your file
 
Response.Write("<h3>HEADER</h3>"); //print out header info
foreach (XAttribute xa in x.Element("Header").Attributes())
    Response.Write(xa.Name + " : " + xa.Value + "<br />");
 
Response.Write("<h3>ITEMS</h3>");//print out item info
foreach (XElement xe in x.Descendants("Item")) //gets each item
{
    foreach (XAttribute xa in xe.Attributes()) //output attributes for item
        Response.Write(xa.Name + ":" + xa.Value + "<br />");
    foreach(XElement xe2 in xe.Descendants()) //output any child elements (ItemType in this example)
        Response.Write(xe2.Name + ":" + xe2.Value + "<br />");
    Response.Write("<br /><br />");//line break
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: tryokanePosted on 2008-07-24 at 23:02:14ID: 22086256

What is 'XElement' and 'XAttribute' above?

 

by: naspinskiPosted on 2008-07-24 at 23:04:19ID: 22086263

they are in the System.Xml.Linq namespace.

using System.Xml.Linq;

                                              
1:

Select allOpen in new window

 

by: naspinskiPosted on 2008-07-24 at 23:07:20ID: 22086277

XElement is just an XML Element:
<PatientBill>
 <Header BillId="Simon Test" BillSubmitDate="2008-07-02" BillSubmitTime="18:06:41Z" />
  <Items><-Items is an element that holds multiple 'Item' Elements and is contained in the 'PatientBIll' Element
 <Item d5p1:type="Episode" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" ItemType="EPISODE" EpisodeId="1" EpisodeDate="2008-07-02" EpisodeTime="18:06:41Z" AdmissionBedCode="B01" AdmissionWard="WD001" />
  <Item d5p1:type="IPMovement" xmlns:d5p1="http://www.w3.org/2001/XMLSchema-instance" IPMovementId="86894" DestinationLocation="QuantaTech Holdings Inc." TransferStartDate="1939-01-17" TransferStartTime="17:04:56Z" TransferToBed="T76" TransferToWard="R1478" TransferToBedType="E5" TransferToRoomType="D8" TransferEndDate="1927-01-21" TransferEndTime="16:09:14Z">
   <ItemType>IPMOVE</ItemType> <--this line is an element (contained within another element)
 </Item>


XAttribute is an attribute (3 attributes bolded below):
<Header BillId="Simon Test" BillSubmitDate="2008-07-02" BillSubmitTime="18:06:41Z" />

 

by: tryokanePosted on 2008-07-24 at 23:08:25ID: 22086281

Can we do the above in framework 2.0?

 

by: naspinskiPosted on 2008-07-24 at 23:13:40ID: 22086306

Yes, with a whole lot more code :P  Any reason you aren't using 3.5 yet?  It is fully backwards compatible and will make your life much, much easier.

 

by: tryokanePosted on 2008-07-24 at 23:18:39ID: 22086318

Can u tell me how to do in 2.0?My environment doesnt use 3.5 framework and vs 2008?

 

by: naspinskiPosted on 2008-07-24 at 23:24:56ID: 22086344

You know you can download it for free and it doesn't require VS 2008
http://www.microsoft.com/downloads/details.aspx?FamilyId=333325FD-AE52-4E35-B531-508D977D32A6&displaylang=en

I don't mean to be harping on it, but it seems silly to me to teach you an old outdated method when there is easier, more useful and effective ways to do this.  It is really to your advantage to not learn outdated methods.

 

by: tryokanePosted on 2008-07-24 at 23:45:37ID: 22086429

Ok thanks,how to select a particular attribute value in the <Items> tag,for ex say under item i wan titemtype,then how can we get this.

 

by: naspinskiPosted on 2008-07-25 at 00:06:06ID: 22086526

Notice that the last 'foreach' statement in my example outputs those.

var itemTypes = from p in x.Descendants("ItemType"); // this will get you a list of all of the ItemTypes
 
//this will get you the 5th Item's 'ItemType'
string itemTypeOfThirdElement = x.Descendants("Item").ToList()[4].Element("ItemType").Value;//gets it
Response.Write("Item Type of 5th 'Item' Element: " + itemTypeOfThirdElement);//prints it

                                              
1:
2:
3:
4:
5:

Select allOpen in new window

 

by: naspinskiPosted on 2008-07-25 at 00:09:20ID: 22086539

explained a little clearer:

var listOfItems = x.Descendants("Item").ToList(); // gets all the 'Item' elements, puts them into a list
XElement Item = listOfItems[4]; // picks the 5th element (0 indexed)
XElement Item_ItemType = Item.Element("ItemType"); // gets the 'ItemType' element
Response.Write("Item Type of 5th 'Item' Element: " + Item_ItemType.Value); //outputs the value

                                              
1:
2:
3:
4:

Select allOpen in new window

 

by: tryokanePosted on 2008-07-25 at 00:31:56ID: 22086611

Now i want to implement the above function in a WCF webservice.How can i do this?

 

by: naspinskiPosted on 2008-07-25 at 00:33:13ID: 22086617

That's a whole different question :)

 

by: tryokanePosted on 2008-07-25 at 00:35:34ID: 22086631

I already placed this question but didnt get enough answers so i m asking u?Do u have an idea?

 

by: tryokanePosted on 2008-07-25 at 01:21:07ID: 22086761

Ok i have installed the framework 3.5 but it is not working.Will i need to install 2005 extensions for frame work 3.5 also?

 

by: naspinskiPosted on 2008-07-25 at 01:22:08ID: 22086765

what isn't working?  Can you be more specific?

 

by: tryokanePosted on 2008-07-25 at 01:23:19ID: 22086774

I was not getting the linq name space when i was typing.

 

by: naspinskiPosted on 2008-07-25 at 01:24:54ID: 22086780

did you include "using System.Xml.Linq;" on the top of your .cs file?

 

by: tryokanePosted on 2008-07-25 at 02:27:27ID: 22087037

yes i was not getting the linq name space when i was typing system.xml.

 

by: naspinskiPosted on 2008-07-25 at 02:30:16ID: 22087049

Did you reboot your system?

 

by: tryokanePosted on 2008-07-25 at 02:32:17ID: 22087054

No i didnt reboot?

 

by: naspinskiPosted on 2008-07-25 at 02:35:01ID: 22087062

give that  try since you just installed a new framework.

 

by: tryokanePosted on 2008-07-25 at 17:20:03ID: 22093104

No it didnt work out.I restarted the system.May be i have to install the vs 2005 extensions for 3. framework also.Is it required also.

 

by: tryokanePosted on 2008-07-26 at 01:14:50ID: 22094170

naspinski:Can u tell me the approach to follow in frame work 2.0.Coding is appreciated.

 

by: tryokanePosted on 2008-07-27 at 03:28:08ID: 22097909

Anyone who can  tell me the approach to follow in frame work 2.0.Coding is appreciated.

 

by: tryokanePosted on 2008-07-28 at 22:39:04ID: 31480114

Thanks for telling me how to do in 3.5 framework.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...