How to use Xpath to insert into xml files - c#

<feed>
<entry>
<data>1234</data>
<content>Stackoverflow</content>
</entry>
</feed>
Next data..
I have to create above xml using xpath in c# is this possible to do..
I had done xml file using below code
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"C:\Log_Data.xml");
XmlElement newelement = xmlDoc.CreateElement("entry");
XmlElement xmldata = xmlDoc.CreateElement("data");
XmlElement xmlcontent = xmlDoc.CreateElement("content");
xmldata.InnerText ="1234" ;
xmlcontent.InnerText ="Stackoverflow";
newelement.AppendChild(xmldata);
newelement.AppendChild(xmlcontent);
xmlDoc.DocumentElement.AppendChild(newelement);
xmlDoc.Save(#"C:\Log_Data.xml");
but i have to use Xpath like we do in sql to write queries like
"Insert into table............."
should it possible in .Net 2.0

XPath is a query language for XML documents. As such, it doesn't provide the capability to alter (delete or insert nodes) an XML document.
One of the most appropriate ways to create or alter an XML document (called XML transformation) is to use XSLT -- a language especially designed for XML transformations.
From C# one can use the .NET XslCompiledTransform class to perform any XSLT 1.0 transformation.
Third party .NET implementations exist for XSLT 2.0.

You have to create your own XPath parser to achieve this. Simple implementation of that can be found here.

Related

Inserting XML nodes and inner nodes to an existing XML document in C#

Currently I have a working C# program that works as follows:
Accept .xls template with values (xls is manually created by user)
Save the values (matching fields) to the database
Convert and write .xls to XML. Please see below sample output:
Existing XML Structure
Now, what I want to do is:
Read the existing xml (the created xml)
Insert another set of nodes and subnodes (ReleaseLine and sub nodes). It must accept multiple ReleaseLine.
Save/create the new xml with appended nodes. Please see below output:
This is what I'm looking for:
My existing C# program is simple but the XML nodes and hierarchy is bloody deep. I just created the C# code using new XElement method and passing values for each nodes. Then I simply use xmlDocument.Save() method to write the xml.
[Existing XML Program][3]
To add nodes or append content in existing xml-data I´d use Linq to XML.
XElement xml = XElement.Load("file.xml");
xml.Add( new XElement("uberNode",
new XElement("childNode", content),
new XElement("anotherChildNode", content)));
xml.Save("file.xml");
Here are some other related solutions.
Add to specific node (with example):
Following exisiting XML-data:
`<Names>
<Name>
<prename>John</prename>
<lastname>Snow</lastname>
</Name>
<Name>
<prename>Harry</prename>
<lastname>Harry</lastname>
</Name>
</Names>`
Now I want to add an "age"-tag before the first "prename"-tag and a "family"-tag after the first "lastname"-tag.
XElement xml = XElement.Load("file.xml");
var childrens = xml.DescendantsAndSelf().ToArray();
var first_prename = childrens[2];
var first_lastname = childrens[3];
Console.WriteLine(childrens[0]); //prints out the whole content
first_prename.AddBeforeSelf(new XElement("age", 22));
first_lastname.AddAfterSelf(new XElement("family", new XElement("mother", "paula"), new XElement("father", "paul")));
xml.Save("file.xml");
Outcome:
`<Names>
<Name>
<age>22</age>
<prename>John</prename>
<lastname>Snow</lastname>
<family>
<mother>paula</mother>
<father>paul</father>
</family>
</Name>
<Name>
<prename>Harry</prename>
<lastname>Harry</lastname>
</Name>
</Names>`
I was facing the problem and Linq gave me the easiest way to accomplish that!
There are also other similar way e.g. here. But I tried a bit more and DescendantsAndSelf() made it easier for me to go through.
I found an answer to my question, here is the link http://www.xmlplease.com/add-xml-linq
Using XPathSelectElement method, I was able to find the right node and appended new block of XElement.

combine two xml_docs C# xmlDocument

I have been using the following SO, How to merge two XmlDocuments in C#, to try and merge two sample xml files into one. Essentially here are my two xml files
test1.xml:
<root>
<Name>
<id>4</id>
<First_name>Tony</First_name>
<last_name>""</last_name>
</Name>
<Name>
<id>6</id>
<First_name>Donny</First_name>
<last_name>Test</last_name>
<middle_name>Ward</middle_name>
</Name>
</root>
And test2.xml
<root>
<Name>
<id>1</id>
<First_name>Nick</First_name>
<last_name>Tester</last_name>
</Name>
<Name>
<id>2</id>
<First_name>Lauren</First_name>
<last_name>MsTester</last_name>
</Name>
</root>
I am using this code snippet it to merge the into the one file but the procedure is not actually combining them. I am a little knew to xmlDocument class and still trying to navigate this issue correctly.
Code:
XmlDocument xmlreader1 = new XmlDocument();
xmlreader1.Load("C:\\Temp\\test1.xml");
XmlDocument xmlreader2 = new XmlDocument();
xmlreader2.Load("C:\\Temp\\test2.xml");
foreach (XmlNode node in xmlreader2.DocumentElement.ChildNodes)
{
XmlNode importedDocument = xmlreader1.ImportNode(node, true);
xmlreader1.DocumentElement.AppendChild(importedDocument);
}
I believe this is correct to take each child node of root (in this case <name>) from test2.xml and append it to test1.xml. I have also tried as:
XmlNode importedDocument = xmlreader1.ImportNode(xmlreader2.DocumentElement, true);
xmlreader1.DocumentElement.AppendChild(importedDocument);
to no avail again any suggestions would be greatly appreciated.
It's not entirely clear what merge operations you need to perform - but if you just need to copy the root node's child elements, that's really simple with LINQ to XML:
XDocument doc1 = XDocument.Load("test1.xml");
XDocument doc2 = XDocument.Load("test2.xml");
doc1.Root.Add(doc2.Root.Elements());
doc1.Save("test3.xml");
This will not perform any actual merging though - if you have elements with the same ID in both files, you'll end up with both elements in the result, rather than one merged element.
Personally I always prefer using LINQ to XML over the old XmlDocument API - I would strongly recommend using it when you have the opportunity to do so.

How to use System.XML.Linq to read simple XML document?

If I have added an XML document to a Visual Studio project, what code using System.XML.Linq will read data elements from this document?
The XDocument class is what you need to load an XML file
string myXmlFile = // path to your Xml file
XDocument myXmlDocument = XDocument.Load(myXmlFile);
It provides methods to query XML trees using LINQ queries, to manipulate in-memory XML trees and to create XML trees from scratch using functional construction
You also try XElement class
XElement doc = XElement.Load(xmlDataFilePath);

Searching in XML Document

What is best way to search in XML document to retrieve one or more records against search criteria. Suggestions are welcomed.
Personally I'd use LINQ to XML if you possibly can. Your question is very vague at the moment, but for example, you could write:
XDocument doc = XDocument.Load("test.xml");
var matches = doc.Descendants("Person")
.Where(x => (string) x.Attribute("Name") == "Jon")
.Where(x => x.Elements("Child").Count() >= 2);
While you can use XPath, I generally prefer not to - it has all the normal problems of embedding one language within another, whereas using LINQ to XML you're using C# throughout, so you have no new syntax to learn - just the relevant methods within the LINQ to XML library.
LINQ to XML also makes namespace handling simple, and you don't need to worry about escaping values etc, as your query is all in code rather than in a string.
.net xml documents have good support for xpath.
It should work for most of your xml searches.
Take a look at XPath Examples
Use XPath by XmlDocument.SelectNodes or SelectSingleNode like this:
XmlDocument doc = new XmlDocument();
doc.Load("bookstore.xml");
XmlNode root = doc.DocumentElement;
// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");
// Select and display the first node in which the author's
// last name is Kingsolver.
XmlNode node = root.SelectSingleNode(
"descendant::bk:book[bk:author/bk:last-name='Kingsolver']", nsmgr);
Console.WriteLine(node.InnerXml);

Converting array of objects to XML in C#

I know there's no built in converter to convert an array of objects to XML. Is there a quick rudimentary way to create a XML out of the array to help me do a LINQ to XML join between this one and another XML I have?
You can use Linq to XML, it is really easy to map from your existing data structures to XML, i.e.:
int[] values = { 1, 2, 17, 8 };
XDocument doc = new XDocument();
doc.Add(new XElement("root", values.Select( x=> new XElement("item", x))));
produces the following output:
<root>
<item>1</item>
<item>2</item>
<item>17</item>
<item>8</item>
</root>
You can always use XmlSerializer to transform a list of C# objects to XML document. The result of the serialization may be customized by using metadata attributes to designate, for example, root nodes or which class property is to be ignored etc... You will definitely need to apply the attributes to make the resulting XML conform as much as possible to your requirements.
Here is a basic tutorial on serializing an Object to XML:

Categories