C # .Net Parsing XML Strings

I read the old topics here, as well as the pages I found on Google, and I can honestly say that it completely confused me. There seem to be around 1,000 ways to parse XML strings using C # .NET, and I don't know what to use. It seems that all the examples that I find depend on a specific root node name, etc.

I have...

<whmcsapi version="4.1.2"> 
 <action>getstaffonline</action> 
 <result>success</result> 
 <totalresults>1</totalresults> 
 <staffonline> 
  <staff> 
   <adminusername>Admin</adminusername> 
   <logintime>2010-03-03 18:29:12</logintime> 
   <ipaddress>127.0.0.1</ipaddress> 
   <lastvisit>2010-03-03 18:30:43</lastvisit> 
  </staff> 
 </staffonline> 
</whmcsapi>

I only need to get values ​​for each employee information (nested in tags). Can someone tell me that the best way to do this is, and perhaps a small example?

Thank!

+5
source share
4 answers
var staff = XDocument.Parse(myXml)
    .Descendants("staff")
    .Select(n => new { 
                         adminusername = n.Element("adminusername").Value,
                         ...
                     });
+12
source

Linq to XML , XML Linq , :

XDocument xmlDoc = XDocument.Load(@"testData.xml");
var    staffMembers = xmlDoc.Descendants("staff")
                        .Select( staff => new { Name = staff.Element("adminusername").Value,
                                                LoginTime = staff.Element("logintime").Value,
                                                IpAddress = staff.Element("ipaddress").Value,
                                                LastVisit = staff.Element("lastvisit").Value,
                                            }).ToList();
+3
XDocument doc = XDocument.Load("staff.xml");

var query = from r in doc.Descendants("staff")
            select new
                   {
                      Adminusername = r.Element("adminusername").Value,
                      LoginTime = r.Element("logintime").Value,
                      IpAddress = r.Element("ipaddress").Value,
                      LastVisit = r.Element("lastvisit").Value
                   };
0
source

Here is the function I'm using that works great for parsing XML files. I have included the "Delimeter" class, which you can use to store XML tags, such as

<startTag></endTag>

Really easy to use and works like a charm ... let me know if you have any questions.

Use the function as follows:

XmlDataManager.List<XmlManager.Delimeter> delimeters = new List<XmlManager.Delimeter>("<result>","</result>"); 
int[] splitIndexArray = { 1 }; // Tells the function where to split in case where the same value occurs multiple times in a line... usually 1 need an entry for each value 
String testValue = "";
List<String> values = new List<String> {testValue}
XmlDataManager.ReadValues(delimeters, values, `<xmlFileNameHere>,` splitIndexArray);

Here is the class:

   public class XmlDataManager 
{
    const String XML_FILE_WRITE_FAIL = "Could not write to xml file";
    const String XML_FILE_READ_FAIL = "Could not read from xml file";
    const String XML_FILE_WRITE_BUILDER_FAIL = "Could not write values to string";  


   /// <summary>
    /// 
    /// </summary>
    public struct Delimeter
    {
        internal String StartDelimeter { get { return _startDelimeter; } }
        internal String EndDelimeter { get { return _endDelimeter; } }
        private readonly String _startDelimeter;
        private readonly String _endDelimeter;

        public Delimeter(String startDelimeter, String endDelimeter)
        {
            _startDelimeter = startDelimeter;
            _endDelimeter = endDelimeter;
        }

        public Delimeter(String startDelimeter)
        {
            _startDelimeter = startDelimeter;
            _endDelimeter = String.Empty;
        }
    }


    public static void ReadValuesLineByLine(    List<Delimeter> elementDelimeters, 
                                                List<String> values, 
                                                String fileName, 
                                                int[] splitIndexes)
    {
        try
        {
            using (StreamReader sr = new StreamReader(fileName))
            {
                String line = sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    for (int i = 0; i <= values.Count-1; i++)
                    {
                        if (line.Contains(elementDelimeters[i].StartDelimeter))
                        {
                            String[] delimeters = { elementDelimeters[i].StartDelimeter, elementDelimeters[i].EndDelimeter };
                            String[] elements = line.Split(delimeters, StringSplitOptions.None);
                            values[i] = elements[splitIndexes[i]];
                        }
                    }
                     line = sr.ReadLine();
                }
            }
        }
        catch(Exception ex)
        {
            throw new Exception(XML_FILE_READ_FAIL, ex);
        }
    }
}

Peter

-3
source

All Articles