0

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;
        }
Edison
  • 79
  • 1
  • 13
  • 2
    You mentioned that you used XmlDocument and failed but haven't shown how exactly you used it. So it is a bit difficult for us to tell you where exactly you failed in your attempt. – Darin Dimitrov May 07 '12 at 07:58
  • I post the code. the debug show string both 2 are null. – Edison May 07 '12 at 08:02
  • You almost done it! :) just fix attribute name. This should work: `OneNode.Attributes["BrowserKind"].Value` – Renatas M. May 07 '12 at 08:07

3 Answers3

0

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 });
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
  • wow, thank u . but I cant find system.xml.linq in the reference? why? – Edison May 07 '12 at 08:14
  • Is your project targeting .NET 3.5 or later? The assembly System.Xml.Linq was added in 3.5. If you are using 3.5 or later, you just have to go to Add Reference and add System.Xml.Linq, then add `using System.Xml.Linq;` to your code. – moribvndvs May 07 '12 at 08:17
0

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;

Jason Williams
  • 56,972
  • 11
  • 108
  • 137
0

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

stefano m
  • 4,094
  • 5
  • 28
  • 27