XML Parsing in C# - c#

I want add the new node as parent node of the old nodes in XML using C#. for example node have the following XMl file:
<bookstore>
<books>
<author>
</author>
</books>
</bookstore>
like that now I want add the new like below:
<bookstore>
<newnode>
<books>
<author>
</author>
</books>
</newnode>
</bookstore>

Try this:-
XmlDocument doc = new XmlDocument();
doc.Load("BookStore.xml");
XmlElement newNode = doc.CreateElement("newnode");
doc.DocumentElement.AppendChild(newNode);
newNode.AppendChild(doc.SelectSingleNode("/bookstore/books"));
doc.Save("BookStore.xml");

Don't have VS here so can't confirm that this works but something like this:
XmlDocument xd = new XmlDocument();
xd.Load("oldxmlfile.xml");
XmlNode oldNode = xd["nameOfRootNode"];
xd.RemoveAll();
XmlNode newParent = xd.CreateNode("nodename");
newParent.AppendChild(oldNode);
xd.AppendChild(newParent);
xd.Save("newXmlFile.xml");

You can clone the old node, append the clone, and remove the original:
(edit; I forgot that AppendChild will move the node if it is already there... no need to clone and remove...)
XmlDocument doc = new XmlDocument();
// load the current xml
doc.LoadXml(xml);
// create a new "newnode" node and add it into the tree
XmlElement newnode = (XmlElement) doc.DocumentElement.AppendChild(doc.CreateElement("newnode"));
// locate the original "books" node and move it
newnode.AppendChild(doc.SelectSingleNode("/bookstore/books"));
// show the result
Console.WriteLine(doc.OuterXml);

Related

Removing CDATA tag from XmlNode

I have an XmlNode which represents the following xml for example:
XmlNode xml.innerText =
<book>
<name><![CDATA[Harry Potter]]</name>
<author><![CDATA[J.K. Rolling]]</author>
</book>
I want to change this node so that it'll contain the following:
XmlNode xml.innerText =
<book>
<name>Harry Potter</name>
<author>J.K. Rolling</author>
</book>
Any ideas?Thanks!
well, if it's exactly how you put it, then it's easy:
xml.innerText = xml.innerText.Replace("![CDATA[","").Replace("]]","");
xmlDoc.Save();// xmlDoc is your xml document
I suggest you to read your entire xml and rewrite it. You can read values without cdata like this
foreach (var child in doc.Root.Elements())
{
string name = child.Name;
string value = child.Value
}

How to update an XML file in C#

I am having an XML file. I would like to create a new node and append it at the end of the XML file and save it back to memory.
<IntCal>
<User>
<Date>12/09/2012</Date>
<Client>abcd</Client>
<Jewellery>Others</Jewellery>
<ROI>7.5</ROI>
<Description>Some Description</Description>
</User>
<IntCal>
I would like to create a new <User> element. Any idea how to do it.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode root_node;
//XmlNodeList nodeList = xmlDoc.SelectNodes("/IntCal/User");
XmlDocument new_node = new XmlDocument();
root_node = xmlDoc.CreateElement("IntCal");
xmlDoc.AppendChild(root_node);
Thanks
Reference: http://msdn.microsoft.com/en-us/library/fw1ys7w6(v=vs.100).aspx
XmlElement elem = xmlDoc.CreateElement("User");
xmlDoc.DocumentElement.AppendChild(elem);
If you want to go the LINQ route, you could do:
XDocument xDoc = XDocument.Load(xmlFile);
xDoc.Element("IntCal")
.Add(new XElement("User"));
Personally, I'd opt for the XDocument and use LINQ but either way works.
Reference: http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
XmlDocument is an old school, why don't you use XDocument, simple and easy:
XDocument xDoc = XDocument.Load(xmlFile);
xDoc.Root.Add(new XElement("User",
new XElement("Client", "John"),
new XElement("Jewellery", "Others")));
xDoc.Save(xmlFile);
References:
XDocument or XmlDocument
Performance: XDocument versus XmlDocument

How to give/add parent node for set of nodes in xmlDocument using vb.net or C#

How to add or give the parent node for set of nodes in xmlDocument using vb.net.
I am having following xml nodes
<books>
<title>title</title>
<isbn>123456</isbn>
<surname>surname</surname>
<givenname>givenname</givenname>
</books>
Now i want to add parent node <author> for <surname> and <givenname> as follows.
<books>
<title>title</title>
<isbn>123456</isbn>
<author>
<surname>surname</surname>
<givenname>givenname</givenname>
</author>
</books>
can any one tell me how to do it in xmlDocument in vb.net.
You need to:
Get the parent node that you want to modify (books).
Add the new child element (author).
Get the child elements you want to move (surname and givenname).
For each node you want to move, remove it from it's parent node (books) and then add it as a child to the new parent node (author).
For instance:
Dim doc As New XmlDocument()
doc.Load(xmlFilePath)
Dim bookToModify As XmlNode = doc.SelectSingleNode("/books")
Dim author As XmlNode = doc.CreateElement("author")
bookToModify.AppendChild(author)
For Each node As XmlNode In bookToModify.SelectNodes("surname | givenname")
node.ParentNode.RemoveChild(node)
author.AppendChild(node)
Next
You can identify the nodes with a call to XPathSelectElements, then remove them from the tree and add them to a new author node.
Example:
Dim xml = <books>
<title>title</title>
<isbn>123456</isbn>
<surname>surname</surname>
<givenname>givenname</givenname>
</books>
Dim author = <author />
xml.Add(author)
For Each node in xml.XPathSelectElements("./givenname|./surname")
node.Remove()
author.Add(node)
Next

Get XML content from XmlNodeList

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");

Adding a node to 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.

Categories

Resources