Search code examples
c#xmlxmldocumentxmlreader

how to get xml .text using c#


here is my xml file

<TEST>
  <Project_Name>browser</Project_Name>  

      <Setting BrowserKind ="Firefox" ></Setting>   

      <ExecuteUrl>http://yahoo.com</ExecuteUrl>

  <caseBox>      
     <test1>apple</test1>
  </caseBox>
</TEST>

this xml means nothing,it's an example. I just want to make some practice.

here are 3 thing i want to get:

(1)Firefox

(2)http://yahoo.com

(3)apple

I use xmldocument, but failed ,nothing I totally get.

how can I get them???

thanks.

this is my test to get firefox

here is my code:

       XmlDocument XmlDoc = new XmlDocument( );
       XmlDoc.Load(here I PLACE THE LOCATION OF FILE);
       XmlNodeList NodeLists = XmlDoc.SelectNodes("TEST/Setting");


        foreach (XmlNode OneNode in NodeLists)
        {

            String StrAttrValue1 = OneNode.Attributes[" Browserkind "].Value;
            String StrAttrValue2 = OneNode.InnerText;
        }

Solution

  • If switching to LINQ to XML is an option, rather than the older Xml API, I'd do it.

    var doc = XDocument.Parse(@"<TEST>
      <Project_Name>browser</Project_Name>  
    
          <Setting BrowserKind =""Firefox"" ></Setting>   
    
          <ExecuteUrl>http://yahoo.com</ExecuteUrl>
    
      <caseBox>      
         <test1>apple</test1>
      </caseBox>
    </TEST>");
    
    
    var result = (from test in doc.Elements("TEST")
                  select new { BrowserKind = test.Element("Setting").Attribute("BrowserKind").Value,
                               ExecuteUrl = test.Element("ExecuteUrl").Value,
                               CaseBox = test.Element("caseBox").Element("test1").Value });