Eray Balkanli
Eray Balkanli

Reputation: 7960

Getting attribute values of a tag in XML via C#

I have an xml document like:

<start>
<action>
<message id="1" result="success">This is my message 1</message>
</action>
<action>
<message id="2" result="failure">This is my message 2</message>
</action>
<action>
<message id="2" result="success">This is my message 3</message>
</action>
</start>

What I need is to count how many Successful and how many Failure message I have in the xml file in SSIS. Importing XML file to SSIS is not allowed now so I added a Script Task in the Control Flow and added the code below to read xml:

XmlDocument doc = new XmlDocument();
doc.Load(Dts.Variables["filename"].Value.ToString());
XmlNode node= doc.SelectSingleNode("/start/action/hl7");
MessageBox.Show(node.Attributes["result"].InnerText);

This is returning the result of the fist message, "success, only; but I want to see the other 2 results (failure, success) as well. It must be because of SelectSingleNode method, but I couldnt find something like SelectMultipleNodes, is there any alternative? I tried the code below but it is giving: Object reference not set to an instance of an object

foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
     //MessageBox.Show(node.InnerText);
     MessageBox.Show(node.Attributes["result"].InnerText);
}

However, note that MessageBox.Show(node.InnerText);shows all three messages inside the xml, but I need its "result" attribute and I couldnt fix the error there. Please also note that using node.Attributes[1].InnerText is giving "index given is out of range" error.

Any help would be appreciated. Thanks.

Upvotes: 0

Views: 265

Answers (2)

Carvo Loco
Carvo Loco

Reputation: 2128

I think the function you are looking for might be XmlNode.SelectNodes.

var successes = doc.SelectNodes("/start/action/message[@result='success']").Count; // = 2
var failures = doc.SelectNodes("/start/action/message[@result='failure']").Count;  // = 1

Upvotes: 1

Charles Mager
Charles Mager

Reputation: 26213

The easiest solution is LINQ to XML. XmlDocument is a lot older and a bit of a pain to work with.

If you want to get the total with success, for example:

var doc = XDocument.Load("filename.xml");

var success = doc.Descendants("message")
    .Attributes("result")
    .Count(result => result.Value == "success");

Upvotes: 1

Related Questions