This is the result of an online xml :
<prices targetNamespace="http://api.saxo.com/v1/prices/">
<price>
<id>28924741-0-0-1-0-1-0</id>
<quantity type="integer">1</quantity>
<normalprice type="decimal">49,95</normalprice>
<price type="decimal">49,95</price>
<vatpercent type="decimal">25,00</vatpercent>
<fixedprice>false</fixedprice>
<discount type="decimal">0,00</discount>
<allowdiscount type="integer">1</allowdiscount>
<productid>28924741</productid>
<entries>
<entry>
<id>1</id>
<type type="PriceEntryType">Standard</type>
<quantity type="integer">1</quantity>
<vatpercent type="decimal">25,00</vatpercent>
<vatamount type="decimal">9,99</vatamount>
<priceunitexvat type="decimal">39,96</priceunitexvat>
<priceunitinclvat type="decimal">49,95</priceunitinclvat>
<pricetotalexvat type="decimal">39,96</pricetotalexvat>
<pricetotalinclvat type="decimal">49,95</pricetotalinclvat>
<discountpercent type="decimal">0,00</discountpercent>
<discountamountexvat type="decimal">0,00</discountamountexvat>
<discountamountinclvat type="decimal">0,00</discountamountinclvat>
</entry>
<entry>
<id>2</id>
<type type="PriceEntryType">Context</type>
<quantity type="integer">1</quantity>
<vatpercent type="decimal">25,00</vatpercent>
<vatamount type="decimal">9,99</vatamount>
<priceunitexvat type="decimal">39,96</priceunitexvat>
<priceunitinclvat type="decimal">49,95</priceunitinclvat>
<pricetotalexvat type="decimal">39,96</pricetotalexvat>
<pricetotalinclvat type="decimal">49,95</pricetotalinclvat>
<discountpercent type="decimal">0,00</discountpercent>
<discountamountexvat type="decimal">0,00</discountamountexvat>
<discountamountinclvat type="decimal">0,00</discountamountinclvat>
</entry>
<entry>
<id>3</id>
<type type="PriceEntryType">Subscription</type>
<quantity type="integer">1</quantity>
<vatpercent type="decimal">25,00</vatpercent>
<vatamount type="decimal">6,99</vatamount>
<priceunitexvat type="decimal">27,96</priceunitexvat>
<priceunitinclvat type="decimal">34,95</priceunitinclvat>
<pricetotalexvat type="decimal">27,96</pricetotalexvat>
<pricetotalinclvat type="decimal">34,95</pricetotalinclvat>
<discountpercent type="decimal">30,03</discountpercent>
<discountamountexvat type="decimal">12,00</discountamountexvat>
<discountamountinclvat type="decimal">15,00</discountamountinclvat>
</entry>
</entries>
</price>
</prices>
I tried many ways to get value of "normalprice" and "pricetotalinclvat" of last entry . but i got null or exception .
Can you guide me that how i can get those two values by using linq ?
Looks like a possible duplication of this
The short version is:
XElement element = XElement.Parse(YourString);
var prices = element.Elements("price")
.Select(item => item.Element("normalprice").Value);
These values can be extracted using Descendant in combination with Last:
var xml = XElement.Parse(xmlStr);
var normalPrice = xml
.Descendants("normalprice")
.Last()
.Value;
var pricetotalinclvat = xml
.Descendants("pricetotalinclvat")
.Last()
.Value;
If approach does not matter, loading the contents into an XDocument and accessing via XPath would seem to make more sense in this situation:
You will want to be using the System.Xml.XPath namespace with this...
System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Parse(xmlString);
decimal priceNormal = 0;
decimal.TryParse(xdoc.XPathSelectElement(#"/prices/price/normalprice").Value, out priceNormal);
decimal priceTotalInclvat = 0;
decimal.TryParse(xdoc.XPathSelectElement(#"/prices/price/entry[last()]/pricetotalinclvat").Value, out priceTotalInclvat);
You can try this:
XDocument doc = XDocument.Load(path);
var query = from price in doc.Descendants("price")
select new
{
NormalPrice = price.Element("normalprice").Value,
PriceTotalInclVat = price.Descendants("entry").Last().Element("pricetotalinclvat").Value
};
To avoid a null exception in case you don't have entries you can also do this:
var query = from price in doc.Descendants("price")
select new
{
NormalPrice = price.Element("normalprice").Value,
PriceTotalInclVat = price.Descendants("entry").Any()?price.Descendants("entry").Last().Element("pricetotalinclvat").Value:"0"
};
Or:
var query = from price in doc.Descendants("price")
let entries = price.Descendants("entry")
select new
{
NormalPrice = price.Element("normalprice").Value,
PriceTotalInclVat = entries!=null ? entries.Last().Element("pricetotalinclvat").Value : "0"
};
I tried all of the solutions in this page but i did not get any result . it is so weird .this is what i did , but it is not a good way :
var document = XDocument.Load(url);
var root = document.Root;
if (root == null)
return;
var ns = root.GetDefaultNamespace();
var mainNode = document.Element(ns + "prices");
if (mainNode == null)
return;
var priceNode = mainNode.Elements(ns + "price").FirstOrDefault().Elements();
var lastEntry = mainNode.Elements(ns + "price").FirstOrDefault().Elements().Last().Elements().Last().Elements();
foreach (var element in lastEntry.Where(element => element.Name.LocalName == "pricetotalinclvat"))
{
plusPrice = element.Value;
}
foreach (var element in priceNode.Where(xElement => xElement.Name.LocalName == "price"))
{
price = element.Value;
}
Any Suggestion to make it better ?
Related
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0" >
</image>
<suggested_pickup>15 minutes after the hour</suggested_pickup>
<suggested_pickup_period>60</suggested_pickup_period>
<temp_f>44.0</temp_f>
<temp_c>6.7</temp_c>
<relative_humidity>55</relative_humidity>
<wind_string>North at 6.9 MPH (6 KT)</wind_string>
<wind_dir>North</wind_dir>
<wind_degrees>340</wind_degrees>
<wind_mph>6.9</wind_mph>
<wind_kt>6</wind_kt>
<pressure_string>1025.2 mb</pressure_string>
<pressure_mb>1025.2</pressure_mb>
<pressure_in>30.28</pressure_in>
<dewpoint_string>28.9 F (-1.7 C)</dewpoint_string>
<dewpoint_f>28.9</dewpoint_f>
<dewpoint_c>-1.7</dewpoint_c>
</current_observation>
I want to get some attributes lik wind_dir,wind_kt etc from the above xml data. I have tried this:
var dayt = GetXMLAsString(WeatherXML);
XDocument doc = XDocument.Parse(dayt);
var r = from element in doc.Elements()
where element.Name == "latitude"
select element;
foreach (var item in r)
{
Console.WriteLine(item.Value);
}
I want this data to be converted into an array or model to send it to ajax result .
I have tried this earlier but kept ".value":
var a = from hash in doc.Descendants("latitude")
select hash.value;
I got proper result when i tried as follows:
XmlDocument WeatherXML = new XmlDocument();
WeatherXML.Load(reader);
var dayt = GetXMLAsString(WeatherXML);
XDocument doc = XDocument.Parse(dayt);
var a = from hash in doc.Descendants("latitude")
select hash;
var asdd = from hash in doc.Descendants("current_observation")
select hash;
With use of System.Xml.Linq namespace we have a set of convenient methods to call.
In your case following code can help:
var doc = XDocument.Parse(WeatherXML);
var value = from e in doc.Elements()
where e.Name == "wind_kt"
select e.Value;
I am trying to get all the Hoop attributes but its only getting the first values(In this instance it is adding 24 and 4 to the listbox). Is there a way of adding all my result to a list. I usually use .ToList() but it did not work in this instant. The aim was to get the hoops for Home and away separate then store it into an object.
XML:
<League>
<Round>
<Match>
<Team Side="Home" >
<Hoop qtr="1st" player-name="Joe" time-scored="24" />
<Hoop qtr="1st" player-name="Jack" time-scored="54" />
</Team>
<Team Side="Away">
<Hoop qtr="1st" player-name="James" time-scored="4" />
<Hoop qtr="1st" player-name="Brown" time-scored="34" />
</Team>
</Match>
</Round>
</League>
C#:
XDocument xDoc = XDocument.Load("test.xml");
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == "Home"
let d = q.Element("Hoop")
select new
{
Period = d.Attribute("qtr").Value,
Name = d.Attribute("player-name").Value,
Time = d.Attribute("time-scored").Value
};
foreach (var qq in query)
{
listBox.Items.Add(qq.Time);
}
Change let d = q.Element("Hoop") to from d in q.Elements("Hoop")
var xDoc = XDocument.Load("test.xml");
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == "Home"
from d in q.Elements("Hoop")
select new
{
Period = d.Attribute("qtr").Value,
Name = d.Attribute("player-name").Value,
Time = d.Attribute("time-scored").Value
};
foreach (var qq in query)
{
listBox.Items.Add(qq.Time);
}
<GetPromotionByIdResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" MajorVersion="2" xmlns="http://fake.com/services">
<Header>
<Response ResponseCode="OK">
<RequestID>1</RequestID>
</Response>
</Header>
<Promotion PromotionId="5200" EffectiveDate="2014-10-10T00:00:00" ExpirationDate="2014-11-16T23:59:00" PromotionStatus="Active" PromotionTypeName="DefaultPromotion">
<Description TypeCode="Long" Culture="en-AU">Promotion Description</Description>
</Promotion>
</GetPromotionByIdResponse>
Im trying to extract this
<Promotion PromotionId="5200" EffectiveDate="2014-10-10T00:00:00" ExpirationDate="2014-11-16T23:59:00" PromotionStatus="Active" PromotionTypeName="DefaultPromotion">
<Description TypeCode="Long" Culture="en-AU">Promotion Description</Description>
</Promotion>
and convert the PromotionId="5200" to PromotionId="XXX"
I can extract the < Promotion > element with the below code but cant work out how to change the attribute
XNamespace xmlResponseNamespace = xmlPromotionResponse.Root.GetDefaultNamespace();
XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("def", xmlResponseNamespace.ToString());
XElement xmlPromotionElement =
xmlPromotionResponse
.Descendants().SingleOrDefault(p => p.Name.LocalName == "Promotion");
You can try this way :
XNamespace ns = "http://fake.com/services";
XElement xmlPromotionElement = xmlPromotionResponse.Descendants(ns+"Promotion")
.SingleOrDefault();
xmlPromotionElement.Attribute("PromotionId").Value = "XXX";
Use simple XNamespace + local-name to reference an element in namespace. Then you can use .Attribute() method to get XAttribute from an XElement and change the attribute's value.
Try this : It returns the value of all attributes in Promotion Tag.
XNamespace ns1 = XNamespace.Get("http://fake.com/services");
var readPromotion = from a in xx.Descendants(ns1 + "Promotion")
select new
{
PromotionID = (string)a.Attribute("PromotionId"),
EffectiveDate = (string)a.Attribute("EffectiveDate"),
ExpirationDate = (string)a.Attribute("ExpirationDate"),
PromotionStatus = (string)a.Attribute("PromotionStatus"),
PromotionTypeName = (string)a.Attribute("PromotionTypeName"),
Description = (string)a.Value
};
foreach (var read in readPromotion)
{
// Read values
}
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();
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();