0

How to get all "cc" attribute values from below xml into a string array

<DD a="1" b="2" c="3">
   <D aa="11" bb="22" cc="33"/>
   <D aa="11" bb="22" cc="33"/>
   <D aa="11" bb="22" cc="33"/>
</DD>  

Cases I tried:

foreach (XmlNode xD in DD) {
                        XmlElement getFDD = (XmlElement)DD;
                        for (int x = 0; x < DD.ChildNodes.Count; x++)
                        {
                            XmlElement XmlFV = (XmlElement)DD.ChildNodes[x];
                            stringArr[x] = XmlFV.GetAttribute("CC");                        
                        }
                    }

And

   for (int u = 0; u < DD.Count; u++)
                    {
                        getFDD = (XmlElement)DD[u].FirstChild;
                        XmlElement getFDD1 = (XmlElement)getFDD;
                        stringArr[u]=getFDD1.GetAttribute("cc");
}

I tried using foreach to loop through each node, i gave up trying that.

0

3 Answers 3

2

This should work for .Net 2.0

var doc = new XmlDocument();
doc.Load(fname);

List<string> list = new List<string>();
foreach(XmlNode node in doc.GetElementsByTagName("D"))
{
    list.Add(node.Attributes["cc"].Value);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it with LINQ2XML:

const string xml = @" 
    <DD a=""1"" b=""2"" c=""3"">
       <D aa=""11"" bb=""22"" cc=""33""/>
       <D aa=""11"" bb=""22"" cc=""33""/>
       <D aa=""11"" bb=""22"" cc=""33""/>
    </DD>";
var doc = XDocument.Parse(xml);
var res = doc.Element("DD")               // Get the root element DD
    .Elements("D")                        // Extract all sub-elements D
    .Select(e => e.Attribute("cc").Value) // Extract attribute cc
    .ToList();

Here is how to do it without LINQ2XML:

XmlReader r = XmlReader.Create(new StringReader(xml));
IList<string> res = new List<string>();
while (r.Read()) {
    if (r.IsStartElement("D")) {
        res.Add(r.GetAttribute("cc"));
    }
}

3 Comments

XDocument.Parse(xml) would be enough
@I4V Thanks for the correction, I keep forgetting about the Parse method even in some of my production code.
dasb: Im sorry i cant use LINQ2XML, i`m using dotnet version 2.0. Is there a way to do using string array??
1

Use Linq2Xml

XElement doc=XElement.Load(yourXmlPath);
String[] attr=doc.Elements("D")
                  .Select(x=>(String)x.Attribute("cc"))
                  .ToArray();

2 Comments

Anirudh: Im sorry i cant use LINQ2XML, i`m using dotnet version 2.0. Is there a way to do using string array??
@Anirudh What about string[] attr :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.