I read through this post.
I have this XML:
<?xml version="1.0" encoding="utf-8" ?>
<Export version="" srcSys="" dstSys="" srcDatabase="" timeStamp="">
</Export>
This is what i tried, but with no luck:
var xml = XElement.Parse(BuyingModule.Properties.Resources.Export);
Func<XElement, string, string> GetAttribute = (e, property) => e.Elements("property").Where(p => p.Attribute("name").Value == property).Single().Value;
var query = from record in xml.Elements("Export")
select record;
var prop = GetAttribute(query.FirstOrDefault(), "version");
How do i access to properties of the "Export" Node?
I need to set those properties
The Export element doesn't have a properties element, which is what your GetAttribute method is trying to find.
My guess is you actually want:
var element = xml.Element("Export"); // Just get the first element
var version = (string) element.Attribute("version");
It's not clear to me why you've used a query expression and a delegate here - it's just things more complicated than you need. But Attribute(XName) is probably what you were missing...
Related
I want to read a config.xml and put each item into a combobox so that the XML file is the datasource. This is my code, which only gives me one entry in my combobox. How do I separate the keys? This is my filter:
C#
var xmlDocument = XDocument.Load(configfile);
var anredeItems = from key in xmlDocument.Descendants("Anrede")
select key.Value.Trim();
anredeNrComboBox.DataSource = anredeItems.ToList();
This is the XML:
<?xml version="1.0"?>
<Config>
<Anrede>
<key_1>Herrn</key_1>
<key_2>Frau</key_2>
<key_3>Herrn Dr.</key_3>
<key_4>Frau Dr.</key_4>
<key_5>Herrn Dr. Med.</key_5>
</Anrede>
</Config>
Your Descendants("Anrede") query will get you the element Andrede, and reading the Value property of that will return the concatenation of all descendant text nodes, which is what you are seeing in your combo box.
What you want are each of its child element values:
var items - doc.Descendants("Anrede")
.Elements()
.Select(x => x.Value.Trim())
.ToList();
You can change your code like this:
var xmlDocument = XDocument.Load(configfile);
var anredeItems = xmlDocument.Root.Elements("Anrede").Elements().Select(p => p.Value.Trim());
anredeNrComboBox.DataSource = anredeItems.ToList();
I searched a long time in order to get an answer but as i can see is not working.
I have an XML File and I would like to read a specific element from a node.
For example, this is the XML:
<Root>
<TV>
<ID>2</ID>
<Company>Samsung</Company>
<Series>13523dffvc</Series>
<Dimesions>108</Dimesions>
<Type>LED</Type>
<SmartTV>Yes</SmartTV>
<OS>WebOS</OS>
<Price>1993</Price>
</TV>
</Root>
I want to get the ID element in the code as a variable so i can increment it for the next item which i will add.
This is the code at this moment, but i can not find a way to select something from the item itself.
XDocument doc = XDocument.Load("C:TVList.XML");
XElement TV = doc.Root;
var lastElement = TV.Elements("TV").Last()
A query for the last TV's id (this will return 0 if there are no elements):
var lastId = (int) doc.Descendants("TV")
.Elements("ID")
.LastOrDefault();
You might also want the highest id (in case they're not in order):
var maxId = doc.Descendants("TV")
.Select(x => (int)x.Element("ID"))
.DefaultIfEmpty(0)
.Max();
See this fiddle for a working demo.
Use like this to get id value
XDocument doc = XDocument.Load(#"C:\TVList.XML");
XElement root = doc.Element("Root");
XElement tv = root.Element("TV");
XElement id = tv.Element("ID");
string idvalue = id.Value;
also make your <Type>LED</Tip> tag of xml to <Type>LED</Type> for match
I'm trying to use the Bing maps API, which returns an XML document. The document (simplified but keeping structure) is
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<StatusCode>
200
</StatusCode>
<ResourceSets>
<ResourceSet>
<Resources>
<TrafficIncident>
<Severity>
Minor
</Severity>
<RoadClosed>
false
</RoadClosed>
</TrafficIncident>
</Resources>
</ResourceSet>
</ResourceSets>
</Response>
In this case, there is only 1 traffic issue but there could be many.
I'm trying to extract if the road is closed and the severity
The XML is stored in a xd object (of type XDocuement)
The following works fine (no error but returns all the elements)
var allNodes = (from x in xd.Descendants()
select x).ToList();
but if I add an element name then it returns a list with 0 items
var allNodes = (from x in xd.Descendants("Resources")
select x).ToList();
I thought the above code is saying:
from xd, grab all of the descendants of the "Resources" element
If my understanding is correct, why does it return 0 results
You must include your (default) XML namespace like so:
var name = XName.Get("Resources", "http://schemas.microsoft.com/search/local/ws/rest/v1");
var allNodes = (from x in xd.Descendants(name)
select x).ToList();
You must not forget the XML Namespace.
XNamespace search = "http://schemas.microsoft.com/search/local/ws/rest/v1";
var allNodes = (from x in xd.Descendants(search + "Resources")
select x).ToList();
<?xml version="1.0" encoding="UTF-8"?>
<meta>
<field type="xs-string" name="AssetId">TF00000002</field>
<field type="xs-string" name="Title">TitleOfAsset</field>
</meta>
I have this XML loaded in to a XDocument using the function
XDocument doc = XDocument.Parse(xmlData)
However, I want to be able to retrieve the text fields "TF00000002" and "TitleOfAsset" ... How do I go about doing this?
templateMetaData.assetID = doc
.Descendants()
.Where(p => p.Name.LocalName == "AssetId")
.ToString();
returns:
System.Linq.Enumerable+WhereEnumerableIterator`1[System.Xml.Linq.XElement]
Can anyone shine a light on this?
In your query, you are calling ToString on an IEnumerable<XElement> which will never give you the expected result, instead look for field elements under your Root and get their value:
var values = doc.Root
.Elements("field")
.Select(element => (string)element);
If you want to access your values using the name attribute you can use Dictionary:
var values = doc.Root
.Elements("field")
.ToDictionary(x => (string)x.Attribute("name"), x => (string)x);
Then you can access the value of AssetId:
var id = values["AssetId"];
Given the following XML, what query can I use to extract the value of preapprovalKey to a string variable? Still a little new to LINQ to XML.
<?xml version="1.0" encoding="UTF-8" ?>
- <ns2:PreapprovalResponse xmlns:ns2="http://svcs.paypal.com/types/ap">
- <responseEnvelope>
<timestamp>2011-04-05T18:35:32.952-07:00</timestamp>
<ack>Success</ack>
<correlationId>7cec030fa3eb2</correlationId>
<build>1655692</build>
</responseEnvelope>
<preapprovalKey>PA-9AG427954Y7578617</preapprovalKey>
</ns2:PreapprovalResponse>
XDocument doc = XDocument.Load("test.xml");
string preapprovalKey = doc.Descendants("preapprovalKey").Single().Value;
See below my exmaple, it help you to resolve your issue and problem. :)
Consider this below XML is there as one of the SQL table's column.
<Root>
<Name>Dinesh</Name>
<Id>2</Id>
</Root>
The objective of the query is to fetch the Name from the XML. In this example we will fetch the 'Dinesh' as the value.
var Query = (from t in dbContext.Employee.AsEnumerable()
where t.active == true
select new Employee
{
Id = t.AtpEventId,
Name = XDocument.Parse(t.Content).Descendants("Root").Descendants("Name").ToList().
Select(node => node.Value.ToString()).FirstOrDefault()
});
Note the following :-
Here in above LINQ , t.active == true is just an example to make some condition if needed.
Please note, in the above LInQ query, always use the AsEnumerable(), as I did in the
first file of the Linq query.exmaple(var Query = (from t in dbContext.Employee.AsEnumerable())
Descendants("Root").Descendants("Name") , Here Root should be the Element matching with the XML, And under the Root we have Name element, thats why we wrote
Descendants("Root").Descendants("Name")
For any further clarification you can reach me via danish.eggericx#gmail.com