I am making windows phone 8 app based the webservices. This is my xml code:
- <response>
<timestamp>2013-10-31T08:30:56Z</timestamp>
<resultsOffset>0</resultsOffset>
<status>success</status>
<resultsLimit>8</resultsLimit>
<resultsCount>38</resultsCount>
- <headlines>
- <headlinesItem>
<headline>City edge past Toon</headline>
<keywords />
<lastModified>2013-10-30T23:45:22Z</lastModified>
<audio />
<premium>false</premium>
+ <links>
- <api>
- <news>
<href>http://api.espn.com/v1/sports/news/1600444?region=GB</href>
</news>
</api>
- <web>
<href>http://espnfc.com/uk/en/report/381799/city-edge-toon?ex_cid=espnapi_public</href>
</web>
- <mobile>
<href>http://m.espn.go.com/soccer/gamecast?gameId=381799&lang=EN&ex_cid=espnapi_public</href>
</mobile>
</links>
<type>snReport</type>
<related />
<id>1600444</id>
<story>Alvardo Negredo and Edin Dzeko struck in extra-time to book Manchester City's place in the last eight of the Capital One Cup, while Costel Pantilimon kept a clean sheet in the 2-0 win to keep the pressure on Joe Hart. </story>
<linkText>Newcastle 0-2 Man City</linkText>
- <images>
- <imagesItem>
<height>360</height>
<alt>Man City celebrate after Edin Dzeko scored their second extra-time goal at Newcastle.</alt>
<width>640</width>
<name>Man City celeb Edin Dzeko goal v nufc 20131030 [640x360]</name>
<caption>Man City celebrate after Edin Dzeko scored their second extra-time goal at Newcastle.</caption>
<type>inline</type>
<url>http://espnfc.com/design05/images/2013/1030/mancitycelebedindzekogoalvnufc20131030_640x360.jpg</url>
</imagesItem>
</images>
Code behind:
myData = XDocument.Parse(e.Result, LoadOptions.None);
var data = myData.Descendants("headlines").FirstOrDefault();
var data1 = from query in myData.Descendants("headlinesItem")
select new UpdataNews
{
News = (string)query.Element("headline").Value,
Desc = (string)query.Element("description"),
Newsurl = (string)query.Element("links").Element("mobile").Element("href"),
Imageurl = (string)query.Element("images").Element("imagesItem").Element("url").Value,
};
lstShow.ItemsSource = data1;
I am trying to get value from xml tags and assign them to News,Desc, etc. Everything works fine except Imageurl, it shows NullException. I tried same method for Imageurl, I don't know what's going wrong.
You arelooking for:
Imageurl=(string)query.Element("images").Element("imagesItem").Element("url").Value
but "imagesItem" is not a child element to "images", it's a sibling.
Edited
Ok, it is probably because the <"url"> element is missing from one of the paths. So, take that into account.
Imageurl=query.Element("images").Element("imagesItem").Element("url") != null ? Imageurl=(string)query.Element("images").Element("imagesItem").Element("url").Value : "no image",
Related
How do I get the values of a node whose immediate ancestor is another node (using descendants method), e.x. below is a small portion of a xml file
<sec id="s2">
<label>2.</label>
<title>THE MORPHOLOGY OF CHONDRAE TENDIANEAE OF ATRIOVENTRICULAR VALVES HEARTS NEWBORNS AND INFANTS</title>
<p>According to the macroscopic</p>
<fig id="F1">
<label>Figure 1.</label>
<caption><p>Tendon string valvular heart baby infants. 1 - mastoid muscle, 2 - tendon strings.</p></caption>
<graphic xlink:href="00062_psisdg9066_90661R_page_2_1.jpg"/>
</fig>
<fig id="F2">
<label>Figure 2.</label>
<caption><p>Tendon string valvular heart newborn baby. 1 - mastoid muscle, 2 - tendon strings.</p></caption>
<graphic xlink:href="00062_psisdg9066_90661R_page_2_2.jpg"/>
</fig>
</sec>
<sec id="s3">
<label>3.</label>
<title>EXPERIMENTAL RESULTS AND DISCUSSION</title>
<p>Material studies provided three-sided and mitral valve that were taken from 8 hearts of stillborn children and four dead infants.</p>
</sec>
I want all the values of the node <label> which has a immediate ancestor node <sec>. i.e. in this case the value should be 2. and 3.
If I do
XDocument doc=XDocument.Load(#"D:\test\sample.XML");
var x = from a in doc.Descendants("label")
where a.Ancestors("sec").Attributes("id").Any()
select a.Value;
I get 2., Figure 1., Figure 2., 3., what other conditions do I have to add to achieve what I want?
Ancestors("sec") will find all ancestors, no matter how deeply nested, not the immediate ancestors, so that's not going to help.
You need to get only the first ancestor. Since Ancestors() will return them in reverse document order, we can simply get the first.
var x = from a in doc.Descendants("label")
let ancestor = a.Ancestors().First()
where ancestor.Name == "sec" && ancestor.Attributes("id").Any()
select a.Value;
I'm currently working on importing XML feed data into our CMS, but am struggling in how to tackle this issue.
For a course, it can have up to 9 staff members looking after it. Each having a name, phone number, email address and type of job. In the CMS for the import, i have 9 sets of these 4 fields, in order to save the data. To get around this, if there is only 5 staff out of 9, i'm targeting an XMLnodelist of course contacts - if it's null, have an empty string, otherwise populate fields.
In the code below, cclist is defined as an xmlnodelist, and test1 gets the full contents of International Admissions as a whole as a string.
What i want to be able to do, using the same format expanded, is for up to 9 course contacts, get the name, email, phone etc of the xmlnodelist item and separate them out, so they can be targeted for the import. I've tried using descendants etc, but can't seem to be able to target these individually, instead of a full string.
Any help would be greatly appreciated. Thanks.
XML
<course>
<dc:description>...</dc:description>
<dc:title>
<![CDATA[ Marketing ]]>
</dc:title>
<learningOutcome>...</learningOutcome>
<test:coursecontacts
<test:contact xsi:type="LeadAcademic">
<test:name
<![CDATA[ Tommy Thompson ]]>
</test:name
<test:phone>0123456789</test:phone>
<test:email>tt#test.com</test:email>
</test:contact>
<test:contact xsi:type="Admissions Administrator">
<test:name>
<![CDATA[ International Admissions ]]>
</test:name>
<test:phone>0123456678</test:phone>
<test:email>ia#test.com</test:email
</test:contact
<test:contact xsi:type="Course Leader">...</test:contact>
<test:contact xsi:type="Admissions Administrator">...</test:contact>
<test:contact xsi:type="Course Administrator">...</test:contact>
</test:coursecontacts>
</course>
C#
protected override FeedCourse MapXmlNodeToEntity(XElement p)
{
var xmlResult = new XmlDocument();
xmlResult.LoadXml(p.ToString());
var test = p.ToString();
var xmlnsManager = new XmlNamespaceManager(xmlResult.NameTable);
xmlnsManager.AddNamespace("ns", "http://xcri.org/profiles/1.2/catalog");
xmlnsManager.AddNamespace("xcriTerms", "http://xcri.org/profiles/catalog/terms");
xmlnsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlnsManager.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
xmlnsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
xmlnsManager.AddNamespace("dcterms", "http://purl.org/dc/terms/");
xmlnsManager.AddNamespace("credit", "http://purl.org/net/cm");
xmlnsManager.AddNamespace("mlo", "http://purl.org/net/mlo");
xmlnsManager.AddNamespace("courseDataProgramme", "http://xcri.co.uk");
xmlnsManager.AddNamespace("test", "http://www.test.com");
var elements = xmlResult.ChildNodes;
var title = xmlResult.DocumentElement.SelectSingleNode("dc:title", xmlnsManager).InnerText;
var description = xmlResult.DocumentElement.SelectSingleNode("dc:description", xmlnsManager).InnerText;
var learningOutcome = xmlResult.DocumentElement.SelectSingleNode("ns:learningOutcome", xmlnsManager).InnerText;
XmlNodeList ccList = xmlResult.DocumentElement.SelectNodes("test:coursecontacts/test:contact", xmlnsManager);
var test1 = ccList.Item(1).InnerText;
// Above line gets full contents of test:contact, but i need down to levels of xsi:type, name, phone and email
}
Had a break away, came back and decided to try a 2d array for this solution. Allows me to get the value i need, so i'm happy. Thanks anyway, and hope this helps someone else.
int contactcount = 0;
String[,] contactsArray = new String[9, 3];
XmlNodeList ccList = xmlResult.DocumentElement.SelectNodes("test:coursecontacts/test:contact", xmlnsManager);
var test1 = ccList.Item(1).InnerText;
foreach (XmlNode xn in ccList)
{
contactsArray[contactcount, 0] = xn["test:name"].InnerText + " ("+ xn["#xsi:type"]+")";
contactsArray[contactcount, 1] = xn["test:phone"].InnerText;
contactsArray[contactcount, 2] = xn["test:email"].InnerText;
contactcount++;
}
var test2 = contactsArray[0,0].ToString()+ contactsArray[0, 1].ToString() + contactsArray[0, 2].ToString();
All the best,
Andy.
I've been looking for a way to watch for the product that have a sales tax from a sale receipt or a invoice in QuickBooks.
I found the property of Salestaxitems, but how i can implement in C# after connecting my app to my company sandbox.
sorry if the question was not very clear and thanks for reading.
Here is the link for creating Invoice with sales tax in C#-
https://gist.github.com/IntuitDeveloperRelations/6500373
I believe you are getting confused with various line details.
Please read this docs for more information n each linedetail type-
https://developer.intuit.com/docs/api/accounting ->Complex Types
Important points to note is that Invoice will have 2 different line for tax and for items.
For Taxes, you need to refer TxnTaxDetail line.
For items, you need to refer SalesItemLineDetail line.
Now SalesItemLinDetail will have a taxCodeRef value of TAX for US companies. When you do a read for an Invoice, loop through the SalesItemLineDetail tag and see if taxCodeRef= TAX is set, then read the corresponding ItemRef value.
The following code can be used to read SalesItemLineDetail-
QueryService<Invoice> bill1QueryService = new QueryService<Invoice>(context);
Invoice bill11 = bill1QueryService.ExecuteIdsQuery("select * from Invoice").FirstOrDefault<Invoice>();
SalesItemLineDetail a1 = (SalesItemLineDetail)bill11.Line[0].AnyIntuitObject;
if(a1.TaxCodeRef.Value=="TAX")
{
string taxCodeid = a1.ItemRef.Value;
object unitprice = a1.AnyIntuitObject;
decimal quantity = a1.Qty;
}
You can create a SalesTax from QBO UI and refer that from an invoice. That way(from the response XML/JSON) you'll get the object structure.
I guess, you are using the official .net devkit(it has all the related properties to construct POCO)
http://developer-static.intuit.com/SDKDocs/QBV3Doc/IPPDotNetDevKitV3/
https://developer.intuit.com/docs?redirectid=acctgNET
Here is a sample:
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2015-02-02T20:36:29.188-08:00">
<QueryResponse startPosition="1" maxResults="1" totalCount="1">
<Invoice domain="QBO" sparse="false">
<Id>1</Id>
<SyncToken>1</SyncToken>
<MetaData>
<CreateTime>2015-02-02T20:34:40-08:00</CreateTime>
<LastUpdatedTime>2015-02-02T20:36:21-08:00</LastUpdatedTime>
</MetaData>
<DocNumber>1001</DocNumber>
<TxnDate>2015-02-02</TxnDate>
<CurrencyRef name="United States Dollar">USD</CurrencyRef>
<Line>
<Id>1</Id>
<LineNum>1</LineNum>
<Description>random dex</Description>
<Amount>20.00</Amount>
<DetailType>SalesItemLineDetail</DetailType>
<SalesItemLineDetail>
<ItemRef name="Services">12</ItemRef>
<UnitPrice>20</UnitPrice>
<Qty>1</Qty>
<TaxCodeRef>TAX</TaxCodeRef>
</SalesItemLineDetail>
</Line>
<Line>
<Amount>20.00</Amount>
<DetailType>SubTotalLineDetail</DetailType>
<SubTotalLineDetail />
</Line>
<TxnTaxDetail>
<TxnTaxCodeRef>2</TxnTaxCodeRef>
<TotalTax>2.25</TotalTax>
<TaxLine>
<Amount>2.25</Amount>
<DetailType>TaxLineDetail</DetailType>
<TaxLineDetail>
<TaxRateRef>1</TaxRateRef>
<PercentBased>true</PercentBased>
<TaxPercent>11.25</TaxPercent>
<NetAmountTaxable>20.00</NetAmountTaxable>
</TaxLineDetail>
</TaxLine>
</TxnTaxDetail>
<CustomerRef name="John Doe">1</CustomerRef>
<SalesTermRef>3</SalesTermRef>
<DueDate>2015-03-04</DueDate>
<TotalAmt>22.25</TotalAmt>
<ApplyTaxAfterDiscount>false</ApplyTaxAfterDiscount>
<PrintStatus>NotSet</PrintStatus>
<EmailStatus>NotSet</EmailStatus>
<Balance>22.25</Balance>
<Deposit>0</Deposit>
<AllowIPNPayment>false</AllowIPNPayment>
<AllowOnlinePayment>false</AllowOnlinePayment>
<AllowOnlineCreditCardPayment>false</AllowOnlineCreditCardPayment>
<AllowOnlineACHPayment>false</AllowOnlineACHPayment>
</Invoice>
</QueryResponse>
</IntuitResponse>
So I have a code that reads partially into an XML document, precenting me with the first block of results which is great, but I have a file containing multiple blocks of the same code & my program seems to quit after the first.
Here's the code:
string path = "data//handling.meta";
var doc = XDocument.Load(path);
var items = doc.Descendants("HandlingData").Elements("Item");//.ToArray();
var query = from i in items
select new
{
HandlingName = (string)i.Element("handlingName"),
Mass = (decimal?)i.Element("fMass").Attribute("value"),
InitialDragCoeff = (decimal?)i.Element("fInitialDragCoeff").Attribute("value"),
PercentSubmerged = (decimal?)i.Element("fPercentSubmerged").Attribute("value"),
DriveBiasFront = (decimal?)i.Element("fDriveBiasFront").Attribute("value"),
InitialDriveGears = i.Element("nInitialDriveGears").Attribute("value")
}
string test = ("{0} - {1}" + query.First().HandlingName + query.First().Mass + query.First().InitialDragCoeff);
richTextBox1.Text = test;
Here's the XML Document :
<?xml version="1.0" encoding="UTF-8"?>
<CHandlingDataMgr>
<HandlingData>
<Item type="CHandlingData">
<handlingName>Car1</handlingName>
<fMass value="140000.000000" />
<fInitialDragCoeff value="30.000000" />
<fPercentSubmerged value="85.000000" />
<vecCentreOfMassOffset x="0.000000" y="0.000000" z="0.000000" />
<vecInertiaMultiplier x="1.000000" y="1.000000" z="1.000000" />
<fDriveBiasFront value="1.000000" />
<nInitialDriveGears value="1" />
</Item>
<Item type="CHandlingData">
<handlingName>Car2</handlingName>
<fMass value="180000.000000" />
<fInitialDragCoeff value="7.800000" />
<fPercentSubmerged value="85.000000" />
<vecCentreOfMassOffset x="0.000000" y="0.000000" z="0.000000" />
<vecInertiaMultiplier x="1.000000" y="1.300000" z="1.500000" />
<fDriveBiasFront value="0.200000" />
<nInitialDriveGears value="6" />
</Item>
</HandlingData>
</CHandlingDataMgr>
As shown, there's multiple handling Name's. The CSharp code above does work, but only for the first block & I'm wondering how to make it read the same values from the different handling name.
I have tried :
if (query.First().HandlingName == "Car2")
{
MessageBox.Show("Car 2 found");
}
but since the message box never appeared, I assume this code doesn't read the hole file?
I'm hoping for output like this:
Name: Car 1
Mass: 140000.000000
InitialDragCoeff: 30.000000
Name: Car 2
Mass: 180000.000000
InitialDragCoeff: 7.800000
My problem in a 'nut shell' : Program does not see Car 2
Any help would be really appreciated, as I've tried many solutions & read many pages regarding XML today
You have:
string test = ("{0} - {1}" + query.First().HandlingName + query.First().Mass
+ query.First().InitialDragCoeff);
that's only ever going to get you the first element, because that's what you asked for.
I think you probably want to loop:
foreach (var item in query) {
var s = "{0} - {1}" + item.HandlingName + query.item.Mass
+ item.InitialDragCoeff
// …
}
I was a long time user of XmlTextReader but after noting that the answer to every related question on here was 'use LINQ' I decided to take the plunge, everything has been going well up until this point. I've been banging my head against this for a while, hopefully someone can help.
I have the following section in my document;
<action_areas>
<time_slice name="0 - 5" id="1">
<action_area id="1">
<aa_team id="1000">9</aa_team>
<aa_team id="1001">7</aa_team>
</action_area>
<action_area id="2">
<aa_team id="1000">5</aa_team>
<aa_team id="1001">2</aa_team>
Due to the structure of the document I need "action_areas" to be the thing passed to the initial selection, ie;
var stuff = from item in xDoc.Descendants("action_areas")
So the question is what statements do I follow that with so I can filter based on the time_slice name attribute AND the action_area id attribute AND the aa_team id attribute so I can ultimately get at the content contained in the aa_team element (9, 7, 5 and 2 in the above instance) with the 'select new' statement?
Thanks in advance.
Try this
string timeSliceToSearchFor = "0 - 5";
string actionAreaToSearchFor = "1";
string aaTeamIdToSearchFor = "1001";
// Returns 7
string value = xDoc .Descendants("action_areas")
.Elements("time_slice")
.Where(element => element.Attribute("name").Value == timeSliceToSearchFor)
.Elements("action_area")
.Where(element => element.Attribute("id").Value == actionAreaToSearchFor)
.Elements("aa_team")
.Where(element => element.Attribute("id").Value == aaTeamIdToSearchFor)
.Single().Value;