简体   繁体   中英

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;
        }

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 });

Xml is case sensitive, so to get a BrowserKind attribute, "browserkind" won't work. It must exactly match the name.

Try this with an xml document:

String apple = doc.DocumentElement["caseBox"]["test1"].InnerText;

it seems there are extra spaces when you write attribute name "Browserkind".. try to remove them. i hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM