Best way to add a string XML snippet into an XML document? - c#

this may have been asked before, but I could not find it.
Suppose I have an XML element
XMLElement nd = xmlDoc.CreateElement("Node");
Now, I would like to add a child to nd with a full XML snippet I get from some other function, like this:
nd.AppendChild("<a1><a2></a2></a1>");
What is the best way to do this?

nb.InnerXML = "<a1><a2></a2></a1>";

The way above is not the "Best" way to do this. The elements are nodes and should be created and added in that fashion. (Not real code, close).
XMLElement nd = xmlDoc.CreateElement("Node");
XMLElement a1 = xmlDoc.CreateElement("Node");
XMLElement a2 = xmlDoc.CreateElement("Node");
//Add the node name etc.
nd.AppendChild(a1);
nd.AppendChild(a2);
It is not good to use "<a1>" strings. What if the namespace changes? What about special characters, don't want to process them yourself, right?

Related

How to find an XPath query to Element/Element without namespaces (XmlSerializer, fragment)?

Assume this simple XML fragment in which there may or may not be the xml declaration and has exactly one NodeElement as a root node, followed by exactly one other NodeElement, which may contain an assortment of various number of different kinds of elements.
<?xml version="1.0">
<NodeElement xmlns="xyz">
<NodeElement xmlns="">
<SomeElement></SomeElement>
</NodeElement>
</NodeElement>
How could I go about selecting the inner NodeElement and its contents without the namespace? For instance, "//*[local-name()='NodeElement/NodeElement[1]']" (and other variations I've tried) doesn't seem to yield results.
As for in general the thing that I'm really trying to accomplish is to Deserialize a fragment of a larger XML document contained in a XmlDocument. Something like the following
var doc = new XmlDocument();
doc.LoadXml(File.ReadAllText(#"trickynodefile.xml")); //ReadAllText to avoid Unicode trouble.
var n = doc.SelectSingleNode("//*[local-name()='NodeElement/NodeElement[1]']");
using(var reader = XmlReader.Create(new StringReader(n.OuterXml)))
{
var obj = new XmlSerializer(typeof(NodeElementNodeElement)).Deserialize(reader);
I believe I'm missing just the right XPath expression, which seem to be rather elusive. Any help much appreciated!
Try this:
/*/*
It selects children of the root node.
Or
/*/*[local-name() = 'NodeElement']
It selects children with local-name() = 'NodeElement' of the root node.
Anyway in your case both expressions select <NodeElement xmlns="">.
walk the tree
foreach(XmlNode node in doc.DocumentElement.childnodes[0].childnodes)
{
// do something with node
}
hideously fragile of course might want to check for nulls here and there.

How can I put the <!CDATA> in a XML tag

I'm trying to put <!CDATA> in a specific tag in my XML file, but the result is <![CDATA[mystring]]>
Someone can help me ?
The encoding
XmlProcessingInstruction pi = doc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
How I'm doing
texto.InnerText = "<![CDATA[" + elemento.TextoComplementar.ToString() + "]]>";
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
XmlCDataSection CData;
InnerText performs whatever escaping is required.
xnode.InnerText = "Hi, How are you..??";
If you want to work with CDATA node then:
CData = doc.CreateCDataSection("Hi, How are you..??");
You haven't explained how you are creating the XML - but it looks like it's via XmlDocument.
You can therefore use CreateCDataSection.
You create the CData node first, supplying the text to go in it, and then add it as a child to an XmlElement.
You should probably consider Linq to XML for working with XML - in my most humble of opinions, it has a much more natural API for creating XML, doing away with the XML DOM model in favour of one which allows you to create whole document trees inline. This, for example, is how you'd create an element with an attribute and a cdata section:
var node = new XElement("root",
new XAttribute("attribute", "value"),
new XCData("5 is indeed > 4 & 3 < 4"));

Find and replace text inside xml document using regular expression

I am using c# console app to get xml document. Now once xmldocument is loaded i want to search for specific href tag:
href="/abc/def
inside the xml document.
once that node is found i want to strip tag completly and just show Hello.
Hello
I think i can simply get the tag using regex. But can anyone please tell me how can i remove the href tag completly using regex?
xml & html same difference: tagged content. xml is stricter in it's formatting.
for this use case I would use transformations and xpath queries rebuild the document. As #Yahia stated, regex on tagged documents is typically a bad idea. the regex for parsing is far to complex to be affective as a generic solution.
The most popular technology for similar tasks is called XPath. (It is also a key component of XQuery and XSLT.) Would the following perhaps solve your task, too?
root.SelectSingleNode("//a[#href='/abc/def']").InnerText = "Hello";
You could try
string x = #"<?xml version='1.0'?>
<EXAMPLE>
<a href='/abc/def'>Hello</a>
</EXAMPLE>";
System.Xml.XmlDocument doc = new XmlDocument();
doc.LoadXml(x);
XmlNode n = doc.SelectSingleNode("//a[#href='/abc/def']");
XmlNode p = n.ParentNode;
p.RemoveChild(n);
System.Xml.XmlNode newNode = doc.CreateNode("element", "a", "");
newNode.InnerXml = "Hello";
p.AppendChild(newNode);
Not really sure if this is what you are trying to do but it should be enough to get you headed in right direction.

Parse XML in C#

Hello I want to know how can I parse this simple XML file content in C#. I can have multiple "in" elements, and from those I want to use date, min, max and state child values.
<out>
<in>
<id>16769</id>
<date>29-10-2010</date>
<now>12</now>
<min>12</min>
<max>23</max>
<state>2</state>
<description>enter text</description>
</in>
<in>
<id>7655</id>
<date>12-10-2010</date>
<now>1</now>
<min>1</min>
<max>2</max>
<state>0</state>
<description>enter text</description>
</in>
</out>
The System.XML namespace has all sorts of tools for parsing, reading, and writing XML data. By the way, your XML isn't well-formed; you've got two <out> elements, but only one </out> element.
Linq to xml is also helpful for parsing xml -
http://msdn.microsoft.com/en-us/library/bb387098.aspx
Also -
http://msdn.microsoft.com/library/bb308960.aspx
You need System.XML, starting with XmlDocument.Load(filename).
Once you have the XmlDocument loaded, you can drill down into it as needed using the built-in .Net XML object model, starting from XmlDocument level. You can walk the tree recursively in a pretty intuitive way, capturing what you want from each XmlNode as you go.
Alternatively (and preferably) you can quickly locate all XmlNodes in your XmlDocument that match certain conditions using XPath - examples here. An example of usage in C# is XmlNode.SelectNodes.
using System;
using System.IO;
using System.Xml;
public class Sample {
public static void Main() {
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']");
//Change the price on the books.
foreach (XmlNode book in nodeList)
{
book.LastChild.InnerText="15.95";
}
Console.WriteLine("Display the modified XML document....");
doc.Save(Console.Out);
}
}
Examples can be found here http://www.c-sharpcorner.com/uploadfile/mahesh/readwritexmltutmellli2111282005041517am/readwritexmltutmellli21.aspx
This might be beyond what you want to do, but worth mentioning...
I hate parsing XML. Seriously, I almost refuse to do it, especially since .NET can do it for me. What I would do is create an "In" object that has the properties above. You probably have one already, or it would take 60 seconds to create. You'll also need a List of In objects called "Out".
Then just deserialze the XML into the objects. This takes just a few lines of code. Here is an example. BTW, this makes changing and re-saving the data just as easy.
How to serialize/deserialize

Find a node in an XML file - performance improvement in C#

Say I need to find a particular node in an XML file, using C#.
<node attribute="my-target-attribute">
"my-target-attribute" is a variable input at runtime.
The node is in no particular place in the XML file, I basically just need to scan the entire XML hierarchy until I find a node with the matching attribute.
Is there any way I can pre-process the XML so finding the node will be faster? I need to keep the original XML structure in place. The XML file could potentially have 10,000 nodes.
You can certainly preprocess the XML to make lookups faster:
Dictionary<string, XmlElement> elementMap = new Dictionary<string, XmlElement>();
AddElementToMap(doc.DocumentElement, elementMap);
...
private void AddElementToMap(XmlElement elm, Dictionary<string, XmlElement> elementMap)
{
elementMap[elm.GetAttribute("attribute")] = elm;
foreach (XmlElement child in elm.SelectNodes("node"))
{
AddElementToMap(child, elementMap);
}
}
Once you've done this, a lookup is simple:
XmlElement elm = elementMap[value];
That code assumes that every element in your document is named "node", that every one has an attribute named "attribute", and that all of the attribute values are unique. The code's more complicated if any of those conditions are untrue, but not exceptionally so.
You could use xslt to transform the xml so that the node is in a known depth. Then when you select with XPath, you can select accordingly without using the // operator.
With VTD-XML (http://vtd-xml.sf.net) you can index the XML document into VTD+XML,
which eliminate the overhead of parsing
http://www.codeproject.com/KB/XML/VTD-XML-indexing.aspx
similar to another answer, you can use xpath similar like selectNodes("//[#attribute='my-target-attribute']"). // will search nodes in all level depths.

Categories