-4

I have to parse following xml in C#

<Packages>
      <Package>
         <PackageName>Create_Staging_Table</PackageName>
         <SequenceID>1</SequenceID>
         <AlwaysRun>True</AlwaysRun>
      </Package>
        <Package>
         <PackageName>Indigo_Staging_Load</PackageName>
         <SequenceID>2</SequenceID>
         <AlwaysRun>True</AlwaysRun>
      </Package>
        <Package>
         <PackageName>Indiogo_Load_Package</PackageName>
         <SequenceID>3</SequenceID>
         <AlwaysRun>True</AlwaysRun>
      </Package>
   </Packages>

I have tried

XmlDocument doc = new XmlDocument();
             doc.Load(filePath);
             XmlNode PackagesListNode = doc.SelectSingleNode("/Packages");
             XmlNodeList Packages = PackagesListNode.SelectNodes("Package");
             foreach (XmlNode node in Packages)
             {
                 TableLoadInstruction instruction = new TableLoadInstruction();
                 instruction.PackageName = node.Attributes.GetNamedItem("PackageName").Value;
                 instruction.Sequence = Convert.ToInt16(node.Attributes.GetNamedItem("SequenceID").Value);
                 instruction.AlwaysRun = Convert.ToBoolean(node.Attributes.GetNamedItem("AlwaysRun").Value);
                 loadInstructions.Add(instruction);
             }

I have got error like "Object reference not set to an instance of an object" at node.Attributes.GetNamedItem("PackageName").value since node.Attributes.GetNamedItem("PackageName") is 'null'

Shankar Kamble
  • 2,983
  • 6
  • 24
  • 40

3 Answers3

1

What you are trying to do won't work because PackageName isn't an attribute. You have to look into the children nodes of Package.

Zebrastorm
  • 81
  • 1
  • 4
1

Finally got solution

XmlDocument doc = new XmlDocument();
             doc.Load(filePath);
             XmlNode PackagesListNode = doc.SelectSingleNode("/Packages");
             XmlNodeList Packages = PackagesListNode.SelectNodes("Package");
             foreach (XmlNode node in Packages)
             {
                 TableLoadInstruction instruction = new TableLoadInstruction();
                 instruction.PackageName = node.SelectSingleNode("PackageName").InnerText;
                 instruction.Sequence = Convert.ToInt16(node.SelectSingleNode("SequenceID").InnerText);
                 instruction.AlwaysRun = Convert.ToBoolean(node.SelectSingleNode("AlwaysRun").InnerText);
                 loadInstructions.Add(instruction);
             }
Shankar Kamble
  • 2,983
  • 6
  • 24
  • 40
0

You are looking for PackageName, that's anode into node.Attributes, so I think you'll never get a value for this xml. Is that your problem?

zeppaman
  • 844
  • 8
  • 23