I am writing a XML using XmlDocument, I need a element or attribute like shown below
The element or attribute required is <?Validversion="1" ?>
how to create using xmldocument or xmlwriter.
// to create <?Validversion="1" ?>
XmlDocument aDoc = new XmlDocument();
aDoc.CreateXmlDeclaration("1.0", "utf-16", null);
XmlCDataSection aDataSec =aDoc.CreateCDataSection("?Version = 2");
aDoc.AppendChild(aDataSec);
aDoc.Save("c:\\vector.xml");
You are looking for XmlDocument.CreateProcessingInstruction and not CDATA section:
var document = new XmlDocument();
document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-16", null));
var piNode = document.CreateProcessingInstruction("Version", "=\"2\"");
document.AppendChild(pi);
Side note: don't forget to AppendChild newly created node.
Related
I have some C# code to open an XML document and to append the XML element to the selected node. However, I need to get copy of a bunch of nodes from one XML document to include them in another XML document.
How can I do this?
my C# code
XmlDocument Formal_TemplateField = new XmlDocument();
XmlDocument BuildMyGridView = new XmlDocument();
Formal_TemplateField.Load(Server.MapPath("~/Formal_TemplateField.xml"));
BuildMyGridView.Load(Server.MapPath("~/BuildMyGridView.xml"));
XmlElement controls = (XmlElement)Formal_TemplateField.SelectSingleNode("controls");
XmlElement Columns = BuildMyGridView.GetElementById("Columns");
Columns.AppendChild(controls); //<--- error here
BuildMyGridView.Save(Server.MapPath("~/BuildMyGridView.xml"));
This code gives me an error (System.NullReferenceException: 'Object reference not set to an instance of an object.')!
What is wrong?
I found the solution and the code will be just like this.
C#
XmlDocument Formal_TemplateField = new XmlDocument();
XmlDocument BuildMyGridView = new XmlDocument();
Formal_TemplateField.Load(Server.MapPath("~/Formal_TemplateField.xml"));
BuildMyGridView.Load(Server.MapPath("~/BuildMyGridView.xml"));
XmlNode NEW_NOOD = BuildMyGridView.ImportNode(Formal_TemplateField.DocumentElement["controls"], true);
BuildMyGridView.DocumentElement.GetElementsByTagName("Columns")[0].AppendChild(NEW_NOOD);
BuildMyGridView.Save(Server.MapPath("~/BuildMyGridView.xml"));
I am currently developing a custom pipeline component for an XML document flow, where the root node and the first child of that root node needs to be stripped off, leaving only the second child node left (which is now the new root node).
I'm using XDocument as container class for the XML document. Ive written some code which gets the second child node, and creates a new XML document with that node as the root, thus removing the two undesired nodes from the picture.
XNode secondChild = xDoc.Root.Elements().First().NextNode;
XDocument outputXml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
secondChild);
But when I test this setup in Biztalk, I only get an empty document back as a response. It seems to create an empty XML document which is then returned.
To give an example of what I want to achieve:
I want to go from a structure like this:
<Root>
<FirstChild></FirstChild>
<SecondChild></SecondChild>
</Root>
To a simple structure like this:
<SecondChild></SecondChild>
The full code of the Execute method in the pipeline:
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
var originalStream = pInMsg.BodyPart.GetOriginalDataStream();
XDocument xDoc; //new XML document to return as the message
using (XmlReader reader = XmlReader.Create(originalStream))
{
reader.MoveToContent();
xDoc = XDocument.Load(reader);
}
XNode secondChild = xDoc.Root.Elements().First().NextNode;
XDocument outputXml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
secondChild);
// Returning stream, serializing the XML to byte array
byte[] output = System.Text.Encoding.ASCII.GetBytes(outputXml.ToString());
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(output, 0, output.Length);
memoryStream.Position = 0;
pInMsg.BodyPart.Data = memoryStream; //overwrite the original message with the modified stream
return pInMsg;
}
Looking around on SO I found this answer, which I tried to follow, but as mentioned it produces an empty document. Is there a different option, other than simply creating a new XDocument?
If you develop a regular map to edit the document you can place it in the maps section of the receive port. It's simpler to create, test, and install than a pipeline component.
Disclaimer: This issue is happening within a Unity application, but AFAIK, this is more of a C# issue than a Unity issue...
I am trying to use System.Xml.XmlDocument to parse an Amazon S3 bucket listing. Here is my bucket xml. I am using an example that I found in a C# Xml tutorial.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("http://rss.cnn.com/rss/edition_world.rss");
XmlNode titleNode = xmlDoc.SelectSingleNode("//rss/channel/title");
if(titleNode != null)
Debug.Log(titleNode.InnerText);
This works fine for that particular XML file, but when I put my stuff in there:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("https://s3.amazonaws.com/themall/");
Debug.Log ( xmlDoc.InnerXml );
XmlNode nameNode = xmlDoc.SelectSingleNode("//Name");
if(nameNode != null)
Debug.Log(nameNode.InnerText);
I get the raw XML in the console, so I know it is being downloaded successfully, but even the simplest XPath produces no results!
My only theory is that perhaps it has something to do with the default namespace in my XML? Do I need to tell XmlDocument about that somehow? Here is my root tag:
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
I have tried creating an XmlNamespaceManager and using it with all of my calls to "SelectSingleNode", but that doesn't seem to work either.
XPathNavigator nav = xmlDoc.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(nav.NameTable);
ns.AddNamespace(System.String.Empty, "http://s3.amazonaws.com/doc/2006-03-01/");
What am I doing wrong?
Thanks!
When you add the namespace to the namespace manager you need to give it a non-empty prefix. According to MSDN:
If the XmlNamespaceManager will be used for resolving namespaces in an XML Path Language (XPath) expression, a prefix must be specified.
Blockquote
The prefix must then be used in your XPath select statement. Here is the code I used and the output was "themall" as expected:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("http://s3.amazonaws.com/themall/");
XmlNamespaceManager namespaceManager =
new XmlNamespaceManager(xmlDoc.NameTable);
namespaceManager.AddNamespace("ns",
"http://s3.amazonaws.com/doc/2006-03-01/");
XmlNode titleNode =
xmlDoc.SelectSingleNode("//ns:Name", namespaceManager);
if (titleNode != null)
Console.WriteLine(titleNode.InnerText);
I have an XmlDocument that is from a webservice, and I want to use a subset of the xml to populate a Gridview control. Unfortunately, it contains extra data that I don't need. So I want to create a new XmlDocument from a subset of the existing xml document.
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlDocResults = ??? //<results><result></result></results>
}
Basically, I want to create a new XmlDocument with the as the root element. Below is a shortened example of the original xml doc:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<query_time>.12</query_time>
<number_results>3</number_results>
<results>
<result><id>1</id></result>
<result><id>2</id></result>
<result><id>3</id> </result>
</results>
</xml>
Anthony's code helped point me in the right direction, but this is what actually worked for me.
XmlDocument xmlResults = new XmlDocument();
XmlDeclaration xmlDec = xmlResults.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootNode = xmlResults.CreateElement("results");
xmlResults.InsertBefore(xmlDec, xmlResults.DocumentElement);
xmlResults.AppendChild(rootNode);
XmlNode node = xmlDoc.GetElementsByTagName("results")[0];
xmlResults.GetElementsByTagName("results")[0].InnerXml = node.InnerXml.ToString();
What you need is ImportNode:-
XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlResults = new XmlDocument();
xmlResults.AppendNode(xmlResults.ImportNode(xmlDoc.SelectSingleNode("/xml/results"));
Untested, but this should be pretty darn close:
XPathDocument original = new XPathDocument("original.xml");
XPathNavigator navigator = original.CreateNavigator();
navigator.MoveToChild("results", "");
XmlWriter results = XmlWriter.Create("results.xml");
navigator.WriteSubtree(results);
results.Close();
And then you can do whatever you need to with the XmlWriter - I'm not sure if you're trying to create the results XmlDocument on disk or not.
I developed a sample application to create an XML document, and I created and saved the XML documented. The application is still running but I delete that XML document and I am now trying to create a new XML using the same application. I got an error of
this document already has 'DocumentElement' node
if (File.Exists(AppPath) == false)
{
root = doc.CreateElement("LicenseDetails");
rootnode = doc.CreateElement("License");
Login = doc.CreateElement("Login_Name");
Login.InnerText = "KSC";
rootnode.AppendChild(Login);
root.AppendChild(rootnode);
doc.AppendChild(root);
doc.Save(AppPath);
}
I can easily append the node in existing XML document but what I want to do is: if my XML got deleted, application has to create a new XML with same tags.
The issue is even if you delete the XML, the doc element you are using is the same one as before. So when you try to add the root element to the doc element exception is thrown. A possible solution is as as follows:
eg:
XmlDocument doc;
XmlElement root;
XmlElement rootnode;
XmlElement Login;
if (File.Exists(#"C:\Test.xml") == false)
{
doc = new XmlDocument();
root = doc.CreateElement("LicenseDetails");
rootnode = doc.CreateElement("License");
Login = doc.CreateElement("Login_Name");
Login.InnerText = "KSC";
rootnode.AppendChild(Login);
root.AppendChild(rootnode);
doc.AppendChild(root);
doc.Save(#"C:\Test.xml");
}
So when you get to this block again it will execute without issues.
Use DocumentElement property - It return the root element of Xml document.
XmlDocument dom=new XmlDocument();
dom.Load("file.xml");
XmlElement ele1=dom.createElement("A");
XmlElement ele2=dom.createElement("B");
ele1.AppendChild(ele2);
dom.DocumentElement.AppendChild(ele1);
dom.Save("file.xml");