I am need bit of help on getting list of xml nodes and printing them.
My code is as below:
XmlDocument doc = new XmlDocument();
doc.Load("To44532.xml");
XmlNode xn = doc.DocumentElement;
foreach (XmlNode xn2 in xn)
{ Console.WriteLine(xn2); }
Console.ReadLine();
I am new to c# please accept my apologies in advance for asking this basic question. So I wanted full list of nodes and then printing them in output.
I ended up with this piece of code because I wanted to debug one of the other code. The idea was that I wanted to display specific nodes in winforms. I tried if statement e.g. :
foreach (XmlNode node in doc.DocumentElement)
{
if (node.Equals("DbtItm"))
{ ..... }
Could you please advise whats the best way to achieve it?
You can select XML Nodes by Name.
<?xml version="1.0" encoding="UTF-8"?>
<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">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
For example to get only book author and book year from as above xml.
XmlDocument xml = new XmlDocument();
xml.Load("XMLFile1.xml");
XmlNodeList xnList = xml.SelectNodes("/bookstore/book");
foreach (XmlNode xn in xnList)
{
string author = xn["author"].InnerText;
string year = xn["year"].InnerText;
Console.WriteLine(author+"-"+year);
}
Related
I am using the below xml file
<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns="urn:newbooks-schema">
<book>
<title>Books</title>
<price>20.00</price>
<attribute>
<fieldName>Books</fieldName>
<attributeStyle>ValueSet</attributeStyle>
<valueset>
<id>Part 1</id>
<values>
<displayName>Lord of the Rings</displayName>
</values>
</valueset>
</attribute>
</book>
<book>
<title>Books</title>
<price>20.00</price>
<attribute>
<fieldName>Books</fieldName>
<valueset>
<id>Part 1</id>
<values>
<displayName>Harry Potter</displayName>
</values>
</valueset>
</attribute>
</book>
</bookstore>
I am trying to get each node "book" in an XMLNodeList and I am looping the nodes to get the individual data of the node "values". I have used the below code and tried to achieve it But the valuenodes is always returning both the values nodes i.e., Lord of the Rings and the Harry Potter together and not in each loop. I want to achieve it one by one in a loop and not all together.
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(text);
var root = xmlDocument.DocumentElement;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");
XmlNodeList criterion = root.SelectNodes("bk:book[bk:title='Books']", nsmgr);
foreach (XmlNode criterionNode in criterion)
{
XmlNode xml = criterionNode.SelectSingleNode("//bk:valueset", nsmgr);
var valuesNodeExpression = "//bk:valueset/bk:values[../../bk:fieldName='Books']";
XmlNodeList valueNodes = criterionNode.SelectNodes(valuesNodeExpression, nsmgr);
}
I slightly refactored the code, giving more telling names to the variables.
// Here the previous code is unchanged.
var books = root.SelectNodes("bk:book[bk:title='Books']", nsmgr);
Console.WriteLine(books.Count);
foreach (XmlNode book in books)
{
var valueset = book.SelectSingleNode(".//bk:valueset", nsmgr);
var id = valueset.SelectSingleNode("./bk:id", nsmgr).InnerText;
var displayName = valueset.SelectSingleNode(".//bk:displayName", nsmgr).InnerText;
Console.WriteLine(id);
Console.WriteLine(displayName);
}
I have a question that may seem very simple, but it's giving me a headache. I have this XML file that has multiple entries, like:
<books>
<book>
<id>1</id>
<firstCover>
<author name="**" age="**" />
<title name="zz" font="yyy" size="uuu"/>
</firstCover>
<lastCover>
</lastCover>
</book>
<book>
<id>2</id>
<firstCover>
<author name="**" age="**" />
<title name="zz" font="yyy" size="uuu"/>
</firstCover>
<lastCover>
</lastCover>
</book>
</books>
Now, in order to get the XML content for first cover of book with id=1, I do this:
XmlNodeList b = root.SelectNodes("/books/book[contains(id,1)]/firstCover");
Then I would really need to take the whole content of what's inside the firstCover for that book :
<author name="**" age="**" />
<title name="zz" font="yyy" size="uuu"/>
and insert it into an XmlElement. This is where I'm stucked. I know I can do it with a foreach loop in XmlNodeList, but is there a more simple way?
I'm guessing you want to actually insert it into an XMLElement in another XMLDocument.
Is this what you are looking for?
XmlDocument sourceDoc = new XmlDocument();
//This is loading the XML you present in your Question.
sourceDoc.LoadXml(xmlcopier.Properties.Resources.data);
XmlElement root = sourceDoc.DocumentElement;
XmlElement b = (XmlElement)root.SelectSingleNode("/books/book[contains(id,1)]/firstCover");
XmlDocument destDoc = new XmlDocument();
XmlElement destRoot = destDoc.CreateElement("base");
destDoc.AppendChild(destRoot);
XmlElement result = destDoc.CreateElement("firstCover");
result.InnerXml = b.InnerXml;
destRoot.AppendChild(result);
destDoc.Save("c:\\test.xml");
the XML
<bookstore xmlns="http://www.contoso.com/books"
xmlns:g="http://www.contoso.com/genre">
<book g:genre="novel" publicationdate="2010-03-01" ISBN="1-123456-15-0">
<title>61 Hours</title>
<author xmlns="http://www.contoso.com/author">
<first-name>Lee</first-name>
<last-name>Child</last-name>
</author>
<price>6.99</price>
</book>
<bookstore>
I need to add a book node to it.. My code reads like this
strpath = "C:\\BookStore.xml";
XmlDocument doc = new XmlDocument();
doc.Load(strpath);
XmlNode root = doc.DocumentElement;
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("b", "http://www.contoso.com/books");
nsMgr.AddNamespace("g", "http://www.contoso.com/genre");
nsMgr.AddNamespace("a", "http://www.contoso.com/author");
// Create a Book element and populate its attributes
System.Xml.XmlElement XmlElementbook = doc.CreateElement("book");
//create the three attributes to hold the values
XmlElementbook.SetAttribute("g:genre";"novel5");
XmlElementbook.SetAttribute("publicationdate", "2010-11-03");
XmlElementbook.SetAttribute("ISBN", "1-00000-00-00");
// Insert the new element into the XML tree
// Create a new XML element and populate its attributes
System.Xml.XmlElement myXmlElementTitle = doc.CreateElement("title");
myXmlElementTitle.InnerText = "TestBook";
// Insert the new element under the node we created
XmlElementbook.AppendChild(myXmlElementTitle);
System.Xml.XmlElement myXmlElementAuthor = doc.CreateElement("author");
myXmlElementAuthor.SetAttribute("xmlns", ("http://www.contoso.com/author"));
System.Xml.XmlElement myXmlElementFirstname = doc.CreateElement("first-name");
myXmlElementFirstname.InnerText = "Bikram";
myXmlElementAuthor.AppendChild(myXmlElementFirstname);
System.Xml.XmlElement myXmlElementLastname = doc.CreateElement("last-name");
myXmlElementLastname.InnerText = "Mann";
myXmlElementAuthor.AppendChild(myXmlElementLastname);
XmlElementbook.AppendChild(myXmlElementAuthor);
// Price
System.Xml.XmlElement myXmlElementPrice = doc.CreateElement("price");
myXmlElementPrice.InnerText = "2.99";
// Insert the new element under the node we created
XmlElementbook.AppendChild(myXmlElementPrice);
//append the whole node to file
doc.DocumentElement.AppendChild(XmlElementbook);
doc.Save("C:\\BookStore.xml");
The only thing is the New node that gets written looks like
<bookstore xmlns="http://www.contoso.com/books"
xmlns:g="http://www.contoso.com/genre">
<book g:genre="novel" publicationdate="2010-03-01" ISBN="1-123456-15-0">
<title>61 Hours</title>
<author xmlns="http://www.contoso.com/author">
<first-name>Lee</first-name>
<last-name>Child</last-name>
</author>
<price>6.99</price>
</book>
***<book genre="novel5"
publicationdate="2010-11-03"
ISBN="1-00000-00-00"
xmlns="">
<title>TestBook</title>
<author xmlns="http://www.contoso.com/author">
<first-name>Bikram</first-name>
<last-name>Mann</last-name>
</author>
<price>2.99</price>
</book>***
<bookstore>
It has an extra XMLNS="" and g: is missing in the node
What Am i doing Wrong Please...
You want:
System.Xml.XmlElement XmlElementbook =
doc.CreateElement("book","http://www.contoso.com/books");
and
XmlElementbook.SetAttribute("genre","http://www.contoso.com/genre","novel5");
to create these nodes in the correct namespaces.
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"
<?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.