Search code examples
c#xmlxmlreader

Locate nodes in XML file


I have fixed my issue with reading the XML files. What I am needing now is to trim the datetime down to just MM dd yyyy hh:mm:ss and not bring the rest of it over when I insert into my Informix database.

This is the XML info:

 <RecordFilingRequestMessage xmlns:nc="http://niem.gov/niem/niem-core/2.0">
<nc:DocumentIdentification>
  <nc:IdentificationID>3212842</nc:IdentificationID>
</nc:DocumentIdentification>
<nc:DocumentPostDate>
  <nc:DateTime>2013-06-25T11:32:08.5343733-04:00</nc:DateTime>
</nc:DocumentPostDate>
<nc:DocumentSubmitter>
  <ecf:EntityPerson s:id="REVIEWER">
    <nc:PersonName />
    <nc:PersonOtherIdentification>
      <nc:IdentificationID>41130</nc:IdentificationID>
      <nc:IdentificationCategoryText>FLEPORTAL</nc:IdentificationCategoryText>
    </nc:PersonOtherIdentification>
    <nc:PersonOtherIdentification>
      <nc:IdentificationID>kacolburn</nc:IdentificationID>
      <nc:IdentificationCategoryText>FLEPORTAL_LOGONNAME</nc:IdentificationCategoryText>
    </nc:PersonOtherIdentification>

...and here is my C# code:

string DocID = null;
        int elementCount = 0;
        string reqID = null;
        string reqDateTime = null;
        string empName = null;
        string[] fileEntries = Directory.GetFiles(@"C:\XML\3212842.xml");
        foreach (string fileName in fileEntries)
        {
            XmlReader xr = XmlReader.Create(fileName); //reads XML from folder
            while (xr.Read())
            {
                if (xr.NodeType == XmlNodeType.Element && xr.Name == "nc:DateTime")
                {
                    reqDateTime = xr.ReadElementContentAsString();                   
                }
                if (xr.NodeType == XmlNodeType.Element && xr.Name == "nc:IdentificationID")
                {
                    elementCount++;
                    DocID = xr.ReadElementContentAsString();
                    if (elementCount == 1)
                    {
                        reqID = DocID;
                    }
                    if (elementCount == 3)
                    {
                        empName = DocID;
                        listBox1.Items.Add(reqID + " / " + reqDateTime + " / " + empName);
                        elementCount = 0;
                        break;
                    }

Solution

  • My first thought is, that the last '/' doesn't belong to the 'SelectNodes' call.

    Alternatively, this code will solve your problem:

    foreach(XmlNode node in xmlDoc.GetElementsByTagName("RecordFilingRequest")[0].GetElementsByTagName("nc:DocumentIdentification"))
    {
        int ID = Convert.ToInt32(node.FirstChild().InnerText);
    }
    

    Edit: This does assume, that 'RecordFilingRequest' always exists. Add a try .. catch statement, if that isn't the case.