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.
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 new to C# programming and trying to update the XML file using C#. Here when I am trying to get the root element using XDocument it is showing the complete script in the file.
Below is my code explanation:
I am having the below function and it is reading the file path from the command line arguments.
private XDocument doc;
public void Update(string filepath)
{
string filename = Path.GetFileName(filepath);
doc = xDocument.Load(filepath);
XElement rootelement = doc.Root;
}
Into the filepath variable, we are taking the path "E:\BuilderTest\COMMON.wxs"
Then we are loading the file using XDocument.
But when we are trying to get the rootelement from the file, it is not showing the root element. Instead, it is showing the complete data in the file.
But when I am using XmlDocument() instead of XDocument() I am able to see only the root element.
Below is the code using XmlDocument():
private XmlDocument doc;
public void Update(string filepath)
{
string filename = Path.GetFileName(filepath);
doc = new XmlDocument();
doc.Load(filepath);
XmlElement rootelement = doc.DocumentElement;
}
Please help me by providing your valuable inputs on this.
XDocument and XmlDocument are different class structure to follow as per requirement.
XDocument will work like below
XDocument doc;
doc = XDocument.Load(filepath);
XElement root = doc.Root;
Root, Descendants, Elements are the operations provided in XDocument. For every node its gives XElement
In your case you should use doc.Root to find the element, then use .Value to get its value
XElement comes with System.Xml.Linq. It is derived from XNode.
It gives you serialized information of every node one by one.
On the other hand XMLDocument will work like below
XmlDocument doc;
doc = new XmlDocument();
doc.Load(filepath);
XmlElement rootelement = doc.DocumentElement;
XmlElement comes with System.Xml. It is derived from XmlNode which is again derived from IEnumerable.
It gives you information in a Enumerable which you can easily parse.
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.
I have to pass a whole XML document into a 3rd party function. The parameter is XmlElement.
To do this until now, I've successfully been using this:
XmlDocument doc;
//doc = ...
XmlElement root = doc.DocumentElement;
3rdPartyFunction(root);
But now I'm using XDocument instead of XmlDocument:
XDocument doc;
//doc = ...
//how to call 3rdPartyFunction?
How do I call the function in this case? Can I convert from "Xml" to "X"?
Use this:
var newDoc = new XmlDocument();
newDoc.LoadXml(doc.ToString());
3rdPartyFunction(newDoc);
[Updated]
XmlDocument xmldoc = new XmlDocument();
using (XmlReader reader = xdoc.CreateReader())
{
xmldoc.Load(reader);
}
XmlElement root = xmldoc.DocumentElement;
3rdPartyFunction(root);
I am using XmlDocument to work with xml
How do I save my "XmlDocument" with my current formatting?
Current formatting:
<?xml version="1.0" encoding="utf-8"?>
<root>
<element></element>
</root>
Code:
XmlDocument testDoc = new XmlDocument();
testDoc.Load(#"C:\Test.xml");
**(do reading/writing using only XmlDocument methods)**
testDoc.Save(#"C:\Test.xml");
There is a similar topic:
XmlDocument class is removing formatting, c#, .NET
The accepted answer is PreserveWhiteSpace = true, which in reality removes all whitespaces instead of preserving them.
Example:
Code:
XmlDocument testDoc = new XmlDocument();
testDoc.Load(#"C:\Test.xml");
testDoc.PreserveWhitespace = true;
testDoc.Save(#"C:\Test.xml");
Result:
<?xml version="1.0" encoding="utf-8"?><root><element></element></root>
Setting PreserveWhitespace to true works for me - but you've got to do it before loading so that the whitespace doesn't get thrown away at load time:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument testDoc = new XmlDocument();
testDoc.PreserveWhitespace = true;
testDoc.Load("Test.xml");
testDoc.Save("Output.xml");
}
}
I've just tried that, and the whitespace was preserved.
Umm. I'm seeing whitespace being preserved when using PreserveWhiteSpace=true. Perhaps it was false when you loaded?
var xmlStr = #"<?xml version=""1.0"" encoding=""utf-8""?>
<root>
<element></element>
</root>";
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
xmlDoc.Save(Console.Out);
Shows:
<?xml version="1.0" encoding="utf-16"?>
<root>
<element></element>
</root>
use preservewhitespace before you load. It will keep formatting same
like above
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
if you will use it after loading. it will kill white spaces in between