0

How do I get the FirstName, LastName and OtherName on the below sample xml file? I need to assign them to a variable from behind code using C#.

  <PatientRecord>
      <Demographics>
              <Names>
                     <cdsd:LegalName namePurpose="L">
                               <cdsd:FirstName>
                                     <cdsd:Part>SARAH</cdsd:Part>
                                     <cdsd:PartType>GIV</cdsd:PartType>
                               </cdsd:FirstName>
                               <cdsd:LastName>
                                      <cdsd:Part>GOMEZ</cdsd:Part>
                                      <cdsd:PartType>FAMC</cdsd:PartType>
                               </cdsd:LastName>
                               <cdsd:OtherName>
                                       <cdsd:Part>GABRIELA</cdsd:Part>
                                       <cdsd:PartType>GIV</cdsd:PartType>
                               <cdsd:PartQualifier>BR</PartQualifier>                  
kjhughes
  • 106,133
  • 27
  • 181
  • 240
zXSwordXz
  • 176
  • 4
  • 15

3 Answers3

0

Load your XML document into an XmlDocument type object and use XPath query the FirstName, LastName etc.

E.g.

XmlDocument doc = new XmlDocument();
doc.LoadXml(yourXmlstring);

XmlNode firstNameNode = doc.DocumentElement.SelectSingleNode("/PatientRecord/Demographics/Names/cdsd:LegalName/cdsd:FirstName"); 

string firstName = firstNameNode.InnerText;

Here's a step by step guide for reading XML document.

Sam
  • 2,917
  • 1
  • 15
  • 28
0
XDocument xml = XDocument.Load(stream);
var legalNames = xml.Root
                    .Elements("Demographics")
                    .Elements("Names")
                    .Elements("LegalName");
foreach(XElement ln in legalNames)
{
    string firstName = (string)ln.Element("FirstName");
    // or you can get (string)ln.Element("FirstName").Element("Part");
    string lastName = (string)ln.Element("LastName");
    string otherName = (string)ln.Element("OtherName");
}

for more information see Programming Guide (LINQ to XML)

Shurick
  • 1
  • 1
0

You can use the ReadXML .net function such as:

DataSet objDataSet = new DataSet();

objDataSet.ReadXML("@PathofXMLfile", XmlReadMode.InferSchema);

List<object> Names = objDataSet.Tables["FirstName"].AsEnumerable().Select(r => r["Part"]).ToList();

This should apply all rows of data in the same tag structure (i.e.: <cdsd:Part>SARAH</cdsd:Part>) into a object list, then you can use a loop to get each value or specify Names[x] to retrieve a value at a specific index. Note: I am not certain if the ReadXML function will remove the tag prefix (cdsd:) or if you will need to include that in the lambda expression i.e.: List<object> Names = objDataSet.Tables["cdsd:FirstName"].AsEnumerable().Select(r => r["cdsd:Part"]).ToList();

gemini6609
  • 332
  • 3
  • 7
  • 21