I have the next code that i developed myself. It works, but if in the XML has 3 records, it will show the three records, but all of them will have the same information that the last one has.
//Load file and puts it on a IEnumerable interface
IEnumerable<MObject> MObjects = XDocument.Load(v_urlDataConnection)
.Element("MTestData").Descendants("book")
.Select(x => new MObject
{
Title = x.Element("title").Value,
Artist = x.Element("artist").Value,
Company = x.Element("company").Value,
Country = x.Element("country").Value,
Year = x.Element("year").Value,
Price = float.Parse(x.Element("price").Value)
}).ToList();
The xml is:
<MTestData>
<book>
<title>Scenes</title>
<artist>Dream Theater</artist>
<company>Vertigo</company>
<country>USA</country>
<year>1999</year>
<price>19.99</price>
</book>
<book>
<title>Falling</title>
<artist>Dream Theater</artist>
<company>3</company>
<country>3</country>
<year>3</year>
<price>3</price>
</book>
<book>
<title>Images and Words</title>
<artist>Dream Theater</artist>
<company>Elektra</company>
<country>USA</country>
<year>1991</year>
<price>15</price>
</book>
</MTestData>
Related
I have this XML File:
<library>
<book ISBN="BSWE153" authors = "AC532" >
<title>Leraing XML</title>
<year>1995</year>
<publisher>W3C</publisher>
</book>
<author id="AC532">
<firstName>Hamdy</firstName>
<middleName/>
<lastName>Taha</lastName>
<nationality>Egypatian</nationality>
</author>
</library>
How to print the information of a book (with its authors information) given by its ISBN?
You can do that using XDocument, for example. You will need to
Parse your string (or load the file)
locate the book
read author Id (or ids?)
locate the author
nicely format it all together - with appropriate checks.
that is just a sketch:
const string xml = #"<?xml version=""1.0""?>
<library>
<book ISBN=""BSWE153"" authors = ""AC532"" >
<title>Leraing XML</title>
<year>1995</year>
<publisher>W3C</publisher>
</book>
<author id=""AC532"">
<firstName>Hamdy</firstName>
<middleName/>
<lastName>Taha</lastName>
<nationality>Egypatian</nationality>
</author>
</library>
";
var doc = XDocument.Parse(xml);
var book = doc.Root.Elements("book")
.FirstOrDefault(b => (string)b.Attribute("ISBN") == "BSWE153" );
var authorId = book.Attribute("authors").Value.ToString();
var author = doc.Root.Elements("author")
.FirstOrDefault(b => (string)b.Attribute("id") == authorId );
Console.WriteLine("{0} by {1} {2}",
book.Element("title").Value,
author.Element("firstName").Value,
author.Element("lastName").Value);
I want to create the following the xml
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
From
List<XElement> Book= xdoc.XPathSelectElements("s0:Name| s0:Author| s0:Price", namespaceManager).ToList();
I am struck in the following place :
XNamespace s0 = "urn:service.Bookstore.com";
XElement root=new XElement(s0 + "BookStore",
new XElement("Book",Book,
);
XDocument result = new XDocument(root);
But this gives the xml structure to be
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
Please help me in getting the expected output.Since the base xml structure looks like this
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
But I want it as two separate instances of
It sounds like you basically need to take the list of elements and group them into groups of 3 elements, putting each group in a Book element:
// The name/author/price elements you're already getting
var elements = ...;
var groups = elements.Select((value, index) => new { value, index })
.GroupBy(pair => pair.index / 3, pair => pair.value);
XNamespace s0 = "urn:service.Bookstore.com";
XDocument result = new XDocument(new XElement(s0 + "BookStore",
groups.Select(g => new XElement("Book", g))));
Try It:
XElement xElement = new XElement("BookStore", new XElement("Book", new XElement("Name", "value"), new XElement("Author", "value"), new XElement("Price", "value")));
xElement.Save("Location.xml");
<bookstore>
<book>
<bookID>100</bookID>
<name> The cat in the hat </name>
</book>
<book>
<bookID>90</bookID>
<name> another book </name>
</book>
<book>
<bookID>103</bookID>
<name> a new book </name>
</book>
</bookstore>
I'm trying to sellect the bookID value from a XML document.The method I currently use is Element(bookID).Value But sometimes the bookID comes as an attribute of book like this: <book bookID=100> Is there a way of doing that in c#, like a xPath expression maybe? Many thanks!
In XPath, you can use union (|) operator to combine query that return different part of the XML. For example :
//book/bookID/text() | //book/#bookID
The above XPath returns text content of bookID element and bookID attribute in document order. See the demo which using XmlDocument.SelectNodes() to execute the XPath.
Demo Codes :
var xml = #"<bookstore>
<book>
<bookID>100</bookID>
<name> The cat in the hat </name>
</book>
<book bookID='90'>
<name> a new book </name>
</book>
<book>
<bookID>103</bookID>
<name> another book </name>
</book>
</bookstore>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var result = doc.SelectNodes("//book/bookID/text() | //book/#bookID");
foreach (XmlNode r in result)
{
Console.WriteLine(r.Value);
}
output :
100
90
103
Does this need to be an XPath expression or can you use Linq with the XDocument system.
For example.
var xDocument = XDocument.Parse(#"<bookstore>
<book>
<bookID>100</bookID>
<name> The cat in the hat </name>
</book>
<book bookID=""90"">
<name> another book </name>
</book>
<book>
<bookID>103</bookID>
<name> a new book </name>
</book>
</bookstore>");
foreach (var xBook in xDocument.Descendants("book"))
{
var bookIdNode = xBook.Elements("bookID").FirstOrDefault();
int bookId = 0;
///there is a book id as an element
if (bookIdNode != null)
{
//invalid book id.. should be an int
if (!int.TryParse(bookIdNode.Value, out bookId))
continue;
}
else
{
var bookIdAttr = xBook.Attributes("bookID").FirstOrDefault();
if (bookIdAttr == null || !int.TryParse(bookIdAttr.Value, out bookId))
continue;
}
if (bookId == 0)
continue;
//else we got our book id
}
This code is quite simple, just enumerates over the descendants with the element name book. It first checks if there is an element named bookID (case sensitive). If there is it attempts to parse the book id out as an int using the method int.TryParse().
If there are no bookID elements it next checks if there are any attributes with the name bookID and grabs the first instance (or null) using FirstOrDefault() extension method. If there is an instance of the bookID attribute it also try to parse the int using the int.TryParse() method.
By the end of the small snippet we have then check if the bookId is 0 if it is zero we can assume something went wrong. However this shouldnt happen as the logic should keep enumerating and forget about Elements without a bookID element or bookID attribute.
Hi all
I have a xml file:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>30</price>
</book>
<book category="CHILDREN">
<title lang="en">abc</title>
<author>bcd</author>
<year>2006</year>
<price>29</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
How to I can get price list when category = "CHILDREN"? I using C#.
example: Output is : price of Harry Potter is 30 and price of abc is 29
Thank,
You can use LINQ to XML. Following code will return collection of anonymous type instances with all data from your XML:
var xDoc = XDocument.Load("Input.txt");
var books = xDoc.Root
.Elements("book")
.Where(b => (string)b.Attribute("category") == "CHILDREN")
.Select(b => new
{
Title = (string)b.Element("title"),
Author = (string)b.Element("author"),
Year = (int)b.Element("year"),
Price = (decimal)b.Element("price")
});
You can call .First() method on books to get only one/first found item.
I have an xml document like the following:
<bookstore>
<book>
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book>
<title>Zen and the Art of Motorcycle Maintenance</title>
<author>
<first-name>Robert</first-name>
<last-name>Pirsig</last-name>
</author>
<price>5.99</price>
</book>
<book>
<title>Other Cities</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Rosenbaum</last-name>
</author>
<price>9.99</price>
</book>
</bookstore>
Of course, the bookstore has more than one book, so I I want to search for an author and then get returned an XElement for the book node that contains the searched author name.
var document = XDocument.Parse(xml);
var bookElements = document.Descendants("book")
.Where(arg => arg.Element("author").Element("first-name").Value == "Benjamin")
.ToList();
or
var bookElements = document.Descendants("first-name")
.Where(arg => arg.Value == "Benjamin")
.Select(arg => arg.Parent.Parent)
.ToList();
[Edit] As you keep editing the question, I will edit the answer :).
To find the first book that meets the criteria:
var foundBookElement = document.Descendants("book")
.Where(arg => arg.Element("author").Element("first-name").Value == "Benjamin")
.FirstOrDefault();
foundBookElement will be null if none of the books match the criteria.