hi i have an xml like this
<?xml version="1.0"?>
<DataSetExchangeWMS xmlns="http://tempuri.org/DataSetExchangeW开发者_JAVA技巧MS.xsd">
<dtObjektInfo>
<LanguageCode>1031</LanguageCode>
<LiegenschaftID>7463</LiegenschaftID>
</dtObjektInfo>
1040 7463 09
Now as i learned from tutorial i get my xml file and select node from descendant.
now why the first foreache does not work? i need to create complicated queries.
XDocument test = XDocument.Load(Server.MapPath("~/XML/objects.xml"));
var objecte = from i in test.Root.Descendants("dtObjektInfo")
select i;
// new test with where
var objecte = from i in test.Descendants( ns + "dtObjektInfo")
where i.Element("LanguageCode").Value == "1031"
select i;
foreach (var item1 in objecte)
{
Response.Write(item1.Value);
}
foreach (XElement item in test.Root.Nodes())
{
Response.Write(item.Value + "<br />");
}
You're not using the XML namespace defined in your XML document!
You need to specify the XML namespace when you query your XML:
XNamespace ns = "http://tempuri.org/DataSetExchangeWMS.xsd";
var objecte = from i in test.Root.Descendants(ns + "dtObjektInfo")
select i;
Marc
Marc has basically sorted your issues out, but i thought i'd throw in some consideration. If you have complicated XML, i would suggest using defined objects. it makes things easier in the long run.
for your example
public class dtObjektInfo
{
public string LanguageCode { get; set; }
public string LiegenschaftID { get; set; }
}
and then your code to call it would turn into
XDocument root = XDocument.Load("c:\\test.xml");
XNamespace ns = "http://tempuri.org/DataSetExchangeWMS.xsd";
dtObjektInfo objecte = (from i in root.Descendants(ns + "dtObjektInfo")
select new dtObjektInfo
{
LanguageCode = i.Element(ns+"LanguageCode").Value,
LiegenschaftID = i.Element(ns+"LiegenschaftID").Value
}).First();
Then you can access the values directly from your dtObjektInfo object. makes coding a lot easier with large xml files as all the work is done in the linq query and then you have a final object.
The benefits of this is that you only have to get the linq right once. coding will be aided by the fact that you are now working with an object whose properties are known (AND INTELLISENSE YAY). all the elements can be cast to the correct types (or exceptions thrown). saving a lot of issues later.
精彩评论