I have a xml structure like this. Can anyone help with a simple linq function to read this xml structure.The itemEntry node repeats according to data. I tried to read the xml using the method below,but i am getting no records in the list. Is this method here correct way to get the details...
List<CX_ITEMLIST> sList =
(from e in XDocument.Load(param.FileName).Root.Elements("itemEntry")
select new CX_ITEMLIST
{
TITLE = (string)e.Element("title"),
YEAR = (string)e.Element("year"),
ITEMNAME = (string)e.Element("itemname"),
CATRYLIST =
(
from p in e.Elements("categorylist").Elements("categories")
select new CATLIST
{
IDTYPE = (string)p.Element("categoryid"),
IDNUMBER = (string)p.Element("categoryName")
}).ToList()
}).ToList();
<itemslist>
<itemInformation>
<itemdate>01/23/2014</itemdate>
<itemcount>57</itemcount>
</itemInformation>
<itemEntry>
<title>Title1</title>
<year>2013</title>
<itemname>testname</itemname>
<categorylist>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
</categorylist>
</itemEntry>
<itemEntry>
<title>Title1</title>
<year>2013</title>
<itemname>testname</itemname>
<categorylist>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
</categorylist>
</itemEntry>
</itemslist>
You should try with XDocument.
XDocument xdoc = XDocument.Load("file.xml");
The System.Xml.XLinq namespace contains some awesome objects to make this easy.
var xDoc = XDocument.Parse(xml); // load your xml string, or use XDocument.Load() to load an xml file
var itemEntries = xDoc
.Root // refers to itemEntries node
.Descendants("itemEntry"); // gets all itemEntry nodes in an IEnumerable object
This gets you an IEnumerable<XNode> of all the itemEntry nodes.
From there you can do what you need, save the values to a business object, etc.
The above method works properly, i found the issue, my xml tag was having namespace attribute. i tried to get the namespace and append it with Elements while reading
XNamespace ns = xDocument.Root.Attribute("xmlns").Value;
List<CX_ITEMLIST> sList =
(from e in XDocument.Load(param.FileName).Root.Elements(ns + "itemEntry")
select new CX_ITEMLIST
{
TITLE = (string)e.Element(ns + "title"),
YEAR = (string)e.Element(ns + "year"),
ITEMNAME = (string)e.Element(ns + "itemname"),
CATRYLIST =
(
from p in e.Elements(ns + "categorylist").Elements(ns + "categories")
select new CATLIST
{
IDTYPE = (string)p.Element(ns + "categoryid"),
IDNUMBER = (string)p.Element(ns + "categoryName")
}).ToList()
}).ToList();
Related
**I have an XML like this-
<?xml version="1.0" encoding="UTF-8"?>
<Tool_Parent>
<tool name="ABCD" id="226">
<category>Centralized</category>
<extension_id>0</extension_id>
<uses_ids>16824943 16824944</uses_ids>
</tool>
<tool name="EFGH" id="228">
<category>Automated</category>
<extension_id>0</extension_id>
<uses_ids>92440 16824</uses_ids>
</tool>
</Tool_Parent>
Based on the id of tool i want to print the uses_ids value,i.e if i search for 228 i should get 92440 16824.
I had tried like-
var toolData = (from toolElement in doc.Descendants("tool")
select new Tool_poco
{
a_Name = tool.Attribute("name").Value,
a_Id = tool.Attribute("id").Value,
e_ExtensionId = tool.Element("extension_id").Value,
e_UsesIds =tool.Element("uses_parm_ids").Value
});
where Tool_poco is a poco class for tool node containing declaration for member variable.
Now I want to get information related to a particular tool id in toolData variable.How to do it?
Note: I have variable like-
searched_Tool_id = Tool_Id_txtBx.Text.ToString();
Please let me know a way through which i can modify my above query for toolData.**
You can modify your query as
Tool_poco toolData = (from el in xelement.Elements("Employee")
where (string)el.Attribute("id") == "226"
select new Tool_poco
{
a_Name = el.Attribute("name").Value,
a_Id = el.Attribute("id").Value,
e_ExtensionId = el.Element("Name").Value,
e_UsesIds = el.Element("uses_ids").Value
}).FirstOrDefault();
You could start by doing something like this once you have an XDocument object loaded and ready:
var xdoc = XDocument.Parse(
#"<?xml version=""1.0"" encoding=""utf-8""?>
<Tool_Parent>
<tool name=""ABCD"" id=""226"">
<category>Centralized</category>
<extension_id>0</extension_id>
<uses_ids>16824943 16824944</uses_ids>
</tool>
<tool name=""EFGH"" id=""228"">
<category>Automated</category>
<extension_id>0</extension_id>
<uses_ids>92440 16824</uses_ids>
</tool>
</Tool_Parent>");
var root = xdoc.Root; // Got to have that root
if (root != null)
{
var id228query = (from toolElement in root.Elements("tool")
where toolElement.HasAttributes
where toolElement.Attribute("id").Value.Equals("228")
let xElement = toolElement.Element("uses_ids")
where xElement != null
select xElement.Value).FirstOrDefault();
Console.WriteLine(id228query);
Console.Read();
}
Output: 92440 16824
**Note: In reference to your example, one possible reason it was not working
for you could be that your xml references an element with name "uses_ids",
however, your query references an element with a similar, but not exact,
spelling with name "uses_parm_ids".**
Hi I have the following XML:
<EPICORTLOG>
<POS>
<ClientId>WkStn.90.1</ClientId>
<Id>POS.90.20140819.251.8279</Id>
<StartTime>2014-08-25T05:12:34</StartTime>
<Store>90</Store>
<SysDate>2014-08-19T00:00:00</SysDate>
<TillNo>1</TillNo>
<Time>2014-08-25T05:12:34</Time>
<Tran>1093</Tran>
<WkStn>1</WkStn>
<WORKSTATION>
<IsAutoLock>1</IsAutoLock>
</WORKSTATION>
<TRADE>
<ITEM>
<Class>102499</Class>
<Desc>NIKE RACER</Desc>
<FinalPrice>82.77</FinalPrice>
<Status>ACTV</Status>
<Style>EV0615</Style>
<Tag>1</Tag>
</ITEM>
</TRADE>
</POS>
</EPICORTLOG>
There are many POS nodes like above in the actual XML. I am trying to fetch the POS node with ID=POS.90.20140819.251.8279 and then the details of Item from that particular node. I have written the following query:
XDocument xdoc = XDocument.Load(XMLFile);
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where items.Attribute("Id").Value == strSelectedPOSID
select new
{
desc=items.Element("ITEM").Attribute("Desc")
};
But it is not yielding any result for me. Here strSelectedPOSID=POS.90.20140819.251.8279. Please let me know where i am going wrong.
Id and Desc are not an Attributes. they are Elements so you should use
var item = from items in xdoc.Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = (string)items.Element("ITEM").Element("Desc")
};
I got the value at last!! Following is what i used:
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = items.Element("TRADE").Element("ITEM").Element("Desc").Value.ToString()
};
Thanks for the inputs.
I am struggling to read this xml file in linq to xml. Can someone help me here.
I need to read each track information.
<playlist version="1" xmlns="http://xspf.org/ns/0/" xmlns:jwplayer="http://developer.longtailvideo.com/trac/wiki/FlashFormats">
<title>Some title here</title>
<creator>Some creater</creator>
<info>somesite.com</info>
<trackList>
<track>
<title>Title 1</title>
<creator>Creater 1</creator>
<location>location 1</location>
</track>
<track>
<title>Title 2</title>
<creator>Creater 2</creator>
<location>location 2</location>
</track>
</trackList>
</playlist>
This is what I am trying to do.
XElement xelement1 = XElement.Load(#"pathtoxmlfile\my.xml");
IEnumerable<XElement> tracks= xelement1.Elements();
// Read the entire XML
foreach (var track in tracks.Descendants("track"))
{
Console.WriteLine(track );
Console.ReadLine();
}
I am using C#.
Thanks
Parminder
Why do you load your document into XElement instead of XDocument?
You have to use XNamespace instance within your query because your document uses default namespace xmlns="http://xspf.org/ns/0/".
var ns = XNamespace.Get("http://xspf.org/ns/0/");
You can use LINQ query to get a collection with your data extracted from XML document. Then you can iterate over that collection and do whatever you need.
var tracks = (from t in xDoc.Root.Element(ns + "trackList").Elements(ns + "track")
select new
{
Title = (string)t.Element(ns + "title"),
Creator = (string)t.Element(ns + "creator"),
Location = (string)t.Element(ns + "location")
}).ToList();
tracks will be a List<T> where T is anonymous type with 3 string properties: Title, Creator and Location.
You forget to include namespace name, do the following changes:
XNamespace defNs = "http://xspf.org/ns/0/";
And
foreach (var track in tracks.Descendants(defNs + "track"))
XElement tracks = XElement.Load(#"pathtoxmlfile\my.xml");
foreach (var track in tracks.Descendants("track"))
{
Console.WriteLine((string)track.Element("title"));
Console.WriteLine((string)track.Element("creator"));
Console.WriteLine((string)track.Element("location"));
}
I am trying to process the following XML:
<rif:Rif xmlns:rif="rif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" rif:numeroRif="XYZXYZXYZ">
<rif:Nombre>Nombre</rif:Nombre>
<rif:AgenteRetencionIVA>SI</rif:AgenteRetencionIVA>
<rif:ContribuyenteIVA>SI</rif:ContribuyenteIVA>
<rif:Tasa />
</rif:Rif>
An I am using the next code:
XDocument doc = XDocument.Parse(result);
var q = from item in doc.Descendants()
let attributeType = item.Attribute("AgenteRetencionIVA").Value
select item;
I have problems to get the attribute rif:AgenteRetencionIVA. How do I to do it?
Looks like tou need to specify custom namespace:
string xml = #"...";
XName nameRif = "rif";
XDocument doc = XDocument.Parse(xml);
var q = from item in doc.Descendants()
let attributeType = item.Attribute(nameRif + "AgenteRetencionIVA")
select item.Value;
var a = q.ToArray();
I’m trying to get the values of an xml snippet that is stored in my database but can’t seem to make it work. They are all coming back null... The xml looks like this:
<fields>
<field id="EmployeeID">1002240002</field>
<field id="JobType">Web Manager</field>
<field id="CompanyCode">R6297C</field>
</fields>
My Code, with the string from the database is below.
string xml = "<fields><field id=\"EmployeeID\">1002240002</field><field id=\"JobType\">Web Manager</field><field id=\"CompanyCode\"> R6297C </field></fields>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var n = xmlDoc.GetElementById("EmployeeID ");
if (n != null)
{
var employeeId = xmlDoc.GetElementById("EmployeeID ").InnerText;
}
Any help on this? I know I am missing something easy here... Thanks!
You can use following XPath query
string xpath = "field[#id='EmployeeID']";
XmlNode fieldNode = xmlDoc.DocumentElement.SelectSingleNode(xpath);
var id = Int32.Parse(fieldNode.InnerText);
Or Linq to Xml
var id = (from f in xdoc.Descendants()
where (string)f.Attribute("id") == "EmployeeID"
select (int)f).Single();
Or with fluent interface
var id = xdoc.Descendants()
.Where(f => (string)f.Attribute("id") == "EmployeeID")
.Select(f => (int)f)
.Single();
BTW xdoc is an instance of XDocument class:
var xdoc = new XDocument(xml);