I want to read the url in the XML Page URLString, and I wrote the following code:
XElement xelement = XElement.Load(URLString);
var list = from y in xelement.Descendants(atom + "entry")
select new {
Link = y.Element(atom + "link").Attribute("href").Value
};
The output of list in the debug is 25 url.
I want to get the items into list. How can I loop through the list to get the items inside it using for, while, foreach, etc.?
It's been a while since I've worked with LINQ, but I think you can do this:
XElement xelement = XElement.Load(URLString);
var items = from y in xelement.Descendants(atom + "entry")
select y.Element(atom + "link").Attribute("href").Value;
var list = items.ToList();
At this point, list will be of type List<string> and you can do whatever you want with it.
Related
I apologize because I'm still in the processes of learning Linq and HtmlAgilityPack, but I'm trying to assign Title and Link to already created string values. In other words, how do I access the values of this .ToList()?
Below is my code:
string imgTitle;
string imgLink;
private void getCaption(string txt)
{
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml("<html><head></head><body>" + txt + "</body></html>");
if (htmlDoc != null)
{
var elements = htmlDoc.DocumentNode.SelectNodes(#"//img[#src]").Select(img => new
{
Link = img.Attributes["src"].Value,
Title = img.Attributes["alt"].Value
}).ToList();
}
imgTitle = elements[0]["Title"]; //I thought i could do this
Sorry for a stupid question but I haven't seen any good explanation out there as to How Linq works and the ToList function. When I print elements[0] I get both values like this, {Link = www.link.url, Title = Some title}
imgTitle = elements[0].Title;
basically when you do
new
{
Link = img.Attributes["src"].Value,
Title = img.Attributes["alt"].Value
}
you are creating an anonymous object with 2 properties.
The list is a list of this anonymous object.
elements[0] gives you the first object. And you can access the 2 properties with elements[0].Link and elements[0].Title
What you really have in elements is a list of an anonymous type that have two properties, so you can access to the Title as follow:
imgTitle = elements[0].Title;
im using a method to parse a xdocument to an object but i have a situation in this line of code:
var xElementTax = xElementXml.Element(xn + "tax");
var aux = xElementTax.Element(xn + "taxNN").Value;
In the taxNN XName the NN part is a random number, i.e: tax01, tax02, tax03 and goes on. It could be any two digit number.
How can i deal with this situation wheres i dont have a fixed tag? The only fixed part of the tag is the tax word.
Thanks.
Are you looping through all the elements of xElementTax?
If so you can just go with this:
foreach(XElement auxElement in xElementTax.Elements)
{
var aux = auxElement.Value;
// And so on
}
If you want only those which match "taxNN" you can go instead with:
foreach(XElement auxElement in xElementTax.Elements.Where(x => x.Name.ToString().StartsWith(xn + "tax"))
{
var aux = auxElement.Value;
...
}
If there's only going to be one of them you can go with:
XElement auxElement = xElementTax.Elements.Where(
x => x.Name.ToString().StartsWith(xn + "tax").FirstOrDefault();
var aux = auxElement.Value;
Please note that I'm new to C# and I learn it right now :) I couldn't find something similar to my problem, so I came here.
I have an application in which I add customers (it's in the final stage). All customers are stored in an XML file. Every single customer gets a new customer number. In my xml file I got an XmlNode called CustNo. Now if the user add a new customer and type in a number which already exist, it should pop up a message box to say that this number already exists. I got this c# code:
XDocument xdoc = XDocument.Load(path + "\\save.xml");
var xmlNodeExist = String.Format("Buchhaltung/Customers/CustNo");
var CustNoExist = xdoc.XPathSelectElement(xmlNodeExist);
if (CustNoExist != null)
{
MessageBox.Show("asdf");
}
And my XML file looks like this:
<Buchhaltung>
<Customers>
<CustNo>12</CustNo>
<Surname>Random</Surname>
<Forename>Name</Forename>
<Addr>Address</Addr>
<Zip>12345</Zip>
<Place>New York</Place>
<Phone>1234567890</Phone>
<Mail>example#test.com</Mail>
</Customers>
<Customers>
<CustNo>13</CustNo>
<Surname>Other</Surname>
<Forename>Forename</Forename>
<Addr>My Address</Addr>
<Zip>67890</Zip>
<Place>Manhattan</Place>
<Phone>0987654321</Phone>
<Mail>test#example.com</Mail>
</Customers>
</Buchhaltung>
But then the message box always pops up. What am I doing wrong?
That's because your XPath return all CustNo elements, no matter of it's content.
Try following:
var myNumber = 12;
var xmlNodeExist = String.Format("Buchhaltung/Customers/CustNo[. = {0}]", myNumber.ToString());
or using First and LINQ to XML:
var myNumber = 12;
var xmlNodeExist = "Buchhaltung/Customers/CustNo";
var CustNoExist = xdoc.XPathSelectElements(xmlNodeExist).FirstOrDefault(x => (int)x == myNumber);
You are currently testing for existance of any 'CustNo' element. See this reference about the XPath syntax.
Your XPath should say something like this:
Buchhaltung//Customers[CustNo='12']
which would say "any customers element containing a 'CustNo' element with value = '12'"
Combining that with your current code:
var custNoGivenByCustomer = "12";
var xmlNodeExistsXpath = String.Format("Buchhaltung//Customers[CustNo='{0}']", custNoGivenByCustomer );
var CustNoExist = xdoc.XPathSelectElement(xmlNodeExistsXpath);
You can use LINQ to XML
var number = textBox1.Text;
var CustNoExist = xdoc.Descendants("CustNo").Any(x => (string)x == number);
if(CustNoExist)
{
MessageBox.Show("asdf");
}
This is because you select the CustNo elements regardless of their value. This will filter it to the desired customer number:
int custNo = 12;
var xmlNodeExist = String.Format("Buchhaltung/Customers[CustNo={0}]", custNo);
It selects the Customers elements instead, but since you're just checking for existence, that's unimportant.
W3Schools has a good tutorial/reference on XPath.
I need to query a list in SharePoint where the columns may be added in the future.
For instance at the moment I have the following columns
Name, Job, interests, address
I want to be able to query this string dynamically using a parameter from the browser so if columns are added in the future I don’t have to change the code but just the parameter.
The address may look like this www.contoso.com/sites/mypage.aspx?property=Interests
And the code something on the line of this:
var SiteParameter = Request.QueryString["property"];
var ItemsFromList = from item in ListItems where item[try to put the parameter in here] select item;
I use SPmetal to get the list details, so if I press item. Visual Studio2010 will return the columns within the list.
This may be easier without SPMetal.
var qy = new SPQuery();
qy.Query =
"<Where><Eq>" +
"<FieldRef Name=`" + siteParameter + "'/>" +
// You may have to worry about the type of the field here, too.
"<Value Type='Text'>" + desiredValue + "</Value>" +
"</Eq></Where>";
var itemCollection = myList.GetItems(qy);
i need to store all the informationen from the xml in an array. My code doesn't work, because I always get just the first item from the xml.
Does anyone know how to fix this?
XDocument xdoc = XDocument.Load("http://www.thefaxx.de/xml/nano.xml");
var items = from item in xdoc.Descendants("items")
select new
{
Title = item.Element("item").Element("title").Value,
Description = item.Element("item").Element("description").Value
};
foreach (var item in items)
{
listView1.Items.Add(item.Title);
}
How about:
var items = from item in xdoc.Descendants("item")
select new
{
Title = item.Element("title").Value,
// *** NOTE: xml has "desc", not "description"
Description = item.Element("desc").Value
};
It is a little hard to be sure without sample xml - but it looks like you intend to loop over all the <item>...</item> elements - which is what the above does. Your original code loops over the (single?) <items>...</items> element(s), then fetches the first <item>...</item> from within it.
edit after looking at the xml; this would be more efficient:
var items = from item in xdoc.Root.Elements("item")
select new {
Title = item.Element("title").Value,
Description = item.Element("desc").Value
};