How do I generate this XML in C#? [duplicate] - c#

This question already has answers here:
Add Stylesheet reference to XML Document in Linq?
(1 answer)
Creating XDocument with xsi:schemaLocation namespace
(1 answer)
Closed last year.
I have an example XML file that I need to generate on the fly in a console application.
This is an example of the first part of the required XML document:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="ABC123.xsl" ?>
<CPPData xsi:noNamespaceSchemaLocation="CPPData_V1.14.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Envelope>
<EnvelopeNode NumOrdre="1">
</EnvelopeNode>
</Envelope>
</CPPData>
I have a method creates and returns an XElement which contains all the data required by the body of the XML (e.g. everything inside the CPPData element).
However I can't figure out how to add the following:
<?xml-stylesheet type="text/xsl" href="ABC123.xsl" ?> to the XDocument
<CPPData xsi:noNamespaceSchemaLocation="CPPData_V1.14.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> to the XElement

var xml = new XDocument();
var xp = new XProcessingInstruction(target: "xml-stylesheet", data: #"type=""text/xsl"" href=""ABC123.xsl""");
xml.Add(xp);
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
xml.Add(new XElement("root",
new XAttribute(ns + "noNamespaceSchemaLocation", "CPPData_V1.14.xsd"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")
));

Related

Access Child nodes with namespace using xpath

How can I read the content of the childnotes using Xpath?
I have already tried this:
var xml = new XmlDocument();
xml.Load("server-status.xml");
var ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ns", "namespace");
var node = xml.SelectSingleNode("descendant::ns:server[ns:ip-address]", ns)
Console.WriteLine(node.InnerXml)
But I only get a string like this:
<ip-address>127.0.0.50</ip-address><name>Server 1</name><group>DATA</group>
How can I get the values individually?
Xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<server-status xmlns="namespace">
<server>
<ip-address>127.0.0.50</ip-address>
<name>Server 1</name>
<group>DATA</group>
</server>
</server-status>
You're using XML namespaces in XPath correctly.
However, your original XPath,
descendant::ns:server[ns:ip-address]
says to select all ns:server elements with ns:ip-address children.
If you wish to select the ns:ip-address children themselves, instead use
descendant::ns:server/ns:ip-address
Similarly, you could select ns:name or ns:group elements.

Removing all child node elements from XML in C#? [duplicate]

This question already has answers here:
how to remove all the childnodes of the specified xmlnode in C# 4.0?
(6 answers)
Closed 5 years ago.
I have the following XML structure:
XML
<?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>
At some point, the <Users> gets filled up with different users, but I want to be able to delete them all in a single, simple function.
Attempt
/// <summary>
/// Removes all nodes from XML creds file on application close
/// </summary>
public static void RemoveXMLData()
{
string xmlPath = Path.Combine(Environment.CurrentDirectory, #"Data\Credential.xml");
XDocument document = XDocument.Load(xmlPath);
document.RemoveNodes();
}
This doesn't seem to be working. I've done the following as well:
Attempt #2
string xmlPath = Path.Combine(Environment.CurrentDirectory, #"Data\Credential.xml");
XDocument document = XDocument.Load(xmlPath);
foreach (var node in document.Descendants("Users"))
{
node.Remove();
}
But this yields an exception error.
At the end of the day, I just want to get back to square one with the following file data:
<?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>
This should work fine:
XDocument document = XDocument.Load(xmlPath);
document.Descendants("Users").Elements().Remove();
As suggested by #Cory, Alternative and faster approach would be:
document.Root.Elements().Remove();
It probably blows up on the second attempt as you are iterating the collection you remove from. Try this.
string xmlPath = Path.Combine(Environment.CurrentDirectory, #"Data\Credential.xml");
XDocument document = XDocument.Load(xmlPath);
var nodes = document.Descendants("Users");
while(nodes.Count > 0)
{
nodes[0].Remove();
}

How to add Namespace and Declaration to the existing XML

how to add Namespace and Declaration to the existing xml.
My XML
<Order>
<child1></child1>
</Order>
Expected
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Order xmlns="http://a.com/a">
<child1></child>
</Order>
Assuming you're only changing the element namespaces and ignoring any attributes, you can parse this using LINQ to XML and then change every element's qualified name:
var doc = XDocument.Parse(xml);
XNamespace ns = "http://a.com/a";
foreach (var element in doc.Descendants())
{
element.Name = ns + element.Name.LocalName;
}

How to update XML file content with XDocument

I have a XML file that contains this:
<?xml version="1.0" encoding="utf-8" ?>
<TokenToCardMapping>
<pair key ="2313123124122512" value="3412412512512512"/>
<pair key ="3414125121259723" value="3749327923749723"/>
</TokenToCardMapping>
I am looking for way to add a new pair element to the TokenToCardMapping descendants with XDocument or XElement.
I have the key and value as strings and I just want to add a new pair.
if my new key and value are: 111111111111 , 222222222222 I want to update the xml to look like this:
<?xml version="1.0" encoding="utf-8" ?>
<TokenToCardMapping>
<pair key ="2313123124122512" value="3412412512512512"/>
<pair key ="3414125121259723" value="3749327923749723"/>
<pair key ="111111111111" value="222222222222"/>
</TokenToCardMapping>
It is easy with LINQ to XML
// create new element
var newElement = new XElement("pair",
new XAttribute("key","111111111111"
new XAttribute("value","222222222222"));
// load the XML Document
var xDoc = XDocument.Load("path");
// Add new element to the root element
xDoc.Root.Add(newElement);
//And save the XML file
xDoc.Save("path")
Note: You need to add a reference to System.Xml.Linq.dll from your project
And I would recommend you read the LINQ to XML tutorial for more details.

How can I add xml attributes with different prefixes/namespaces in C#?

I need to be able to create an XML Document that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rootprefix:rootname
noPrefix="attribute with no prefix"
firstprefix:attrOne="first atrribute"
secondprefix:attrTwo="second atrribute with different prefix">
...other elements...
</rootprefix:rootname>
Here's my code:
XmlDocument doc = new XmlDocument();
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
doc.AppendChild(declaration);
XmlElement root = doc.CreateElement("rootprefix:rootname", nameSpaceURL);
root.SetAttribute("schemaVersion", "1.0");
root.SetAttribute("firstprefix:attrOne", "first attribute");
root.SetAttribute("secondprefix:attrTwo", "second attribute with different prefix");
doc.AppendChild(root);
Unfortunately, what I'm getting for the second attribute with the second prefix is no prefix at all. It's just "attrTwo"--like the schemaVersion attribute.
So, is there a way to have different prefixes for attributes in the root element in C#?
This is just a guide for you. May be you can do:
NameTable nt = new NameTable();
nt.Add("key");
XmlNamespaceManager ns = new XmlNamespaceManager(nt);
ns.AddNamespace("firstprefix", "fp");
ns.AddNamespace("secondprefix", "sp");
root.SetAttribute("attrOne", ns.LookupPrefix("fp"), "first attribute");
root.SetAttribute("attrTwo", ns.LookupPrefix("sp"), "second attribute with different prefix");
This will result in:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rootprefix:rootname schemaVersion="1.0" d1p1:attrOne="first attribute" d1p2:attrTwo="second attribute with different prefix" xmlns:d1p2="secondprefix" xmlns:d1p1="firstprefix" xmlns:rootprefix="ns" />
Hope this will be of any help!
I saw a post on another question that ended up solving the issue. I basically just created a string that had all the xml in it, then used the LoadXml method on an instance of XmlDocument.
string rootNodeXmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<rootprefix:rootname schemaVersion=\"1.0\" d1p1:attrOne=\"first attribute\""
+ "d1p2:attrTwo=\"second attribute with different prefix\" xmlns:d1p2=\"secondprefix\""
+ "xmlns:d1p1=\"firstprefix\" xmlns:rootprefix=\"ns\" />";
doc.LoadXml(rootNodeXmlString);

Categories

Resources