XML Parsing in windows phone - c#

I have to parse XML,for that have used some code that's working but problem is not we have nested XML this code is unable to parse all data.So please suggest me how to part this.
XML
<Author>
<Book id="101" name="Computer" subcategories="2">
<Book id="600" name="java" subcategories="0" contents="10 books"/>
<Book id="601" name="php" subcategories="0" contents="5 books"/>
</Book>
<Book id="201" name="Language" subcategories="2">
<Book id="700" name="Hindi" subcategories="0" contents="6 books"/>
<Book id="701" name="English" subcategories="0" contents="4 books"/>
</Book>
<Book id="301" name="Music" subcategories="2">
<Book id="800" name="life" subcategories="0" contents="10 books"/>
<Book id="801" name="Wild" subcategories="0" contents="5 books"/>
</Book>
<Book id="401" name="Story" subcategories="2">
<Book id="900" name="My Life" subcategories="0" contents="1 books"/>
<Book id="901" name="One Day" subcategories="0" contents="1 books"/>
</Book>
</Author>
Parser method:
public void parser()
{
XElement nodes = XElement.Load("file.xml");
var node = from nd in nodes.DescendantNodes() select nd;
foreach (XElement nds in node)
{
string name = nds.Attribute("name").Value;
int id=Convert.ToInt32(nds.Attribute("id").Value);
MessageBox.Show("" + name);
MessageBox.Show("" + id);
if (nds.HasElements)
{
getChild(nds.DescendantNodes(),id);
}
}
public void getChild(IEnumerable<XNode> node,int id)
{
foreach (XElement nds in node)
{
IEnumerable<XNode> nd=from list in nds.DescendantNodes() select list;
int temp = Convert.ToInt32(ids);
foreach (XElement ss in nd)
{
string name = ss.Attribute("name").Value;
MessageBox.Show("" + name);
}
if (nds.HasElements)
{
getChild(nds.DescendantNodes(),id);
}
}
}
I have above XML and have used above code for parse.

Perhaps you're looking for this:
XElement doc = XElement.Parse(#"<Author>
<Book id=""101"" name=""Computer"" subcategories=""2"">
<Book id=""600"" name=""java"" subcategories=""0"" contents=""10 books""/>
<Book id=""601"" name=""php"" subcategories=""0"" contents=""5 books""/>
</Book>
<Book id=""201"" name=""Language"" subcategories=""2"">
<Book id=""700"" name=""Hindi"" subcategories=""0"" contents=""6 books""/>
<Book id=""701"" name=""English"" subcategories=""0"" contents=""4 books""/>
</Book>
<Book id=""301"" name=""Music"" subcategories=""2"">
<Book id=""800"" name=""life"" subcategories=""0"" contents=""10 books""/>
<Book id=""801"" name=""Wild"" subcategories=""0"" contents=""5 books""/>
</Book>
<Book id=""401"" name=""Story"" subcategories=""2"">
<Book id=""900"" name=""My Life"" subcategories=""0"" contents=""1 books""/>
<Book id=""901"" name=""One Day"" subcategories=""0"" contents=""1 books""/>
</Book>
</Author>");
var query = doc.Descendants();
foreach(XElement ele in query){
Console.WriteLine(string.Format("Name: {0}\nValue: {1}\n",ele.Name.LocalName.ToString(),ele));
if (ele.HasAttributes){
var query1 = ele.Attributes();
foreach (XAttribute att in query1)
{
Console.WriteLine(string.Format("Attribute: {0}\nValue: {1}\n", att.Name.LocalName.ToString(), att.Value));
};
};
};

Related

How to get special data from xml file using c#

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.

Replace element in xdocument placed in a treeview with another xelement

I have a simple xmlfile and that is placed in a treeview
<bookstore xmlns="generic">
<book genre="Book" >`
<title>Book of Benjamin Franklin</title>
<author>
<first-name>Benson</first-name>
<last-name>Frank</last-name>
</author>
<price>89.88</price>
</book>
<book genre="autobiography">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Ben</first-name>
<middlename />
<last-name>Franklin</last-name>
</author>
<price>89.88</price>
</book>
<book genre="novel" >
<title>The Confidence Man</title>
<author>
<first-name>John</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
</bookstore>
I want to replace (2nd element)
<book genre="autobiography" >
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Ben</first-name>
<middlename />
<last-name>Franklin</last-name>
</author>
<price>89.88</price>
</book>
with an another element(that is edited and i have edited portion as a string)
<book genre="autobiography">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Ben</first-name>
<last-name>Franklin</last-name>
</author>
<price>89.88</price>
</book>
Code I used is here
XElement XmlTree = XElement.Parse(text);//text contain edited portion
XmlElement XMLE = (XmlElement)TreeV.SelectedItem;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(scd_file);
XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
xfrag.InnerXml = text;
XmlDocumentFragment xfrag1 = xdoc.CreateDocumentFragment();
xfrag1.InnerXml = XMLE.OuterXml;
xdoc.ReplaceChild(xfrag, xfrag1);
But it shows error (xfrag1 is not a node of xdoc)
please help me to solve this problem.
thank u all i got the solution.
XmlElement XMLE = (XmlElement)TreeV.SelectedItem;// selection from treeview(TreeV) that we want to edit (2nd element)
XmlDocument XD = new XmlDocument();
XD.LoadXml(text);// text is edited part save as a string
XmlNode root=XD.DocumentElement;
XmlDocument xml = XMLE.ParentNode.OwnerDocument;
XmlNode import= xml.ImportNode(root, true);
XMLE.ParentNode.ReplaceChild(import, XMLE);
xml.Save(scd_file); //scd_file path

Getting the previous node of a searched keyword in xml

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.

Reading XML file in C# with XpathNavigator

I am trying to read the book.xml file provided as an example on the MSDN website.
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
<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 genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
I have the following code until now:
static void Main()
{
XmlDocument document = new XmlDocument();
document.Load(#"c:\books.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/bookstore/book");
while (nodes.MoveNext())
{
Console.WriteLine(nodes.Current.HasAttributes);
}
}
It seems this code is reading everything, but from here on if I want to display, say, just the titles of all book etc., how do I access them?
You can iterate over the titles if you change the XPath expression to select all title nodes:
XPathDocument document = new XPathDocument(#"c:\tmp\smpl5.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/bookstore/book/title");
foreach (XPathNavigator item in nodes)
{
Console.WriteLine(item.Value);
}
Note that you don't need to create an XmlDocument if you don't plan to modify the document. Using an XPathDocument is usually more light-weight.
you can also use this "//title" instead of "/bookstore/book"

C# How to extract complete xml node set

<?xml version="1.0" encoding="ISO-8859-1"?>
<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>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</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>
Is their any way using XPath to select the complete first node set, for example from
<book category="COOKING">
to
</book>,
so that, that chunk of xml can be stored for later use.
Bob.
Let's say this XML is stored in an XmlDocument called doc.
XmlElement docRoot = doc.DocumentElement;
XmlNode cookingNode = docRoot.SelectSingleNode("./book[#category='COOKING']");
I tested this and added this line to verify:
Console.WriteLine(cookingNode.OuterXml);
Here was the output:
<book category="COOKING"><title lang="en">Everyday Italian</title><author>Giada
De Laurentiis</author><year>2005</year><price>30.00</price></book>
This query will select that node. Are you trying to get a set of nodes or just the single one? You might have to put the bookstore node back yourself if you only want th subset of nodes.
/bookstore/book[#category='COOKING']
as XmlDocument ...
var x = new XmlDocument();
x.Load("XmlFile1.xml");
var ns = x.SelectSingleNode("/bookstore/book[#category='COOKING']");
var res = ns.OuterXml;
as XDocument ...
var x = XDocument.Load("XmlFile1.xml");
var root = new XElement("bookstore",
from book in x.Element("bookstore").Elements("book")
where book.Attribute("category").Value == "COOKING"
select book
);
if you just want the book node you can do this instead of the root version above
var book = x.Element("bookstore")
.Elements("book")
.Where(n => n.Attribute("category").Value == "COOKING")
.First();
suppose I want to extract only the data wherethe xml file is as follows ..
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author auth="up">Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
the final result on the list view should look like this
lang auth
en up
I have coded as follows ..
XmlNodeList elemList = doc.GetElementsByTagName("book");
for (int j = 0; j < elemList.Count; j++)
{
if (elemList[j].Attributes["category"].Value == "COOKING")
{
XmlNodeList elemList1 = doc.GetElementsByTagName("author");
for (int i = 0; i < elemList1.Count; i++)
{
string attrVal = elemList1[i].Attributes["lang"].Value;
string attrVal1 = elemList1[i].Attributes["auth"].Value;
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(attrVal1);
lvi.SubItems.Add(attrVal1);
}
listView1.Items.Add(lvi);
}
}
}
Adding to Matthew's response:
XmlDocument xDoc = new XmlDocument();
// (Put code to populate xDoc here)
XmlNodeList xNode = xDoc.SelectNodes(#"/bookstore/book[#category='COOKING']");
xNode now equals Book of type COOKING.

Categories

Resources