I want to retrieve data from XML(which have also an xsd file) using C#. What can it be wrong with my code: My Xml file look likes this.
<Model_1 xmlns="http://www.3ds.com/xsd/3DXML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.3ds.com/xsd/3DXML ./3DXML.xsd">
<Header>
<item></item>
<item1></item1>
<item2></item2>
</Header>
<Product>
<otheritem></otheritem>
<otheritem1></otheritem1>
<otheritem2></otheritem2>
</Product>
<Books>
<otheritem></otheritem>
<otheritem1></otheritem1>
<otheritem2></otheritem2>
</Books>
</Model_1>
...c#
XDocument xdoc = Document.Load("document.xml") var items = from item in xdoc.Descendants("Header")
select new
{
_Item= item.Element("Item").Value,
_Item1= item.Element("Item1").Value,
_Item2= item.Element("Item2").Value,
};
foreach (var item in items)
{
Item= item._Item;
Item1 = item._Item1;
Item2 = item.Item2;
}
Console.WriteLine("show me :" + Item+ " + " + Item1 + " + " + Item2);
How can I extract just items from Header and not Product or Books?
You need to use namespace:
var ns = xdoc.Root.GetDefaultNamespace();
var header = xdoc.Root.Element(ns + "Header");
Also keep in mind - you have lower case item
in your xml, not Item
:
Item = (string)header?.Element(ns + "item");
Item1 = (string)header?.Element(ns + "item1");
Item2 = (string)header?.Element(ns + "item2");
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.