XML Namespace prefix only on root - c#

I am creating an XML document using the Task Factory XML Output Destination task though the output needs some tweaking and I can't seem to find a way to do this within the task so figured I would be able to do this via the script component with C#.
This is the XML I am working with
<?xml version="1.0" encoding="utf-8"?>
<CSDS xmlns="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
<CYP000>
<C000010>1.0</C000010>
</CYP000>
</CSDS>
And I need to change the XML to look like:
<?xml version="1.0" encoding="utf-8"?>
<CSDS:CSDS xmlns:CSDS="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
<CYP000>
<C000010>1.0</C000010>
</CYP000>
</CSDS>
I have tried creating a new XDocument declaring the namespace and adding the source elements in but this adds the namespace to all elements.
string xmlFile = #"C:\Temp\csds.xml";
string newXmlFile = #"C:\Temp\csds-new.xml";
XDocument sourceXml = XDocument.Load(xmlFile);
XNamespace ns = "http://www.datadictionary.nhs.uk/messages/CSDS-v1-0";
XDocument newXml = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement newRoot = new XElement(ns + "CSDS",
new XAttribute(XNamespace.Xmlns + "CSDS", ns.NamespaceName));
newRoot.Add(sourceXml.Root.Elements());
newRoot.Save(newXmlFile);
Output
<?xml version="1.0" encoding="utf-8"?>
<CSDS:CSDS xmlns:CSDS="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
<CSDS:CYP000>
<CSDS:C000010>1.0</CSDS:C000010>
</CSDS:CYP000>
</CSDS:CSDS>

I have found that doing the following after loading my file works along with the rest of my code:
foreach (var descendants in sourceXml.Root.Descendants())
descendants.Name = descendants.Name.LocalName;

Related

XML dynamic SiteMap asp.net

I tried to make dynamic Site Map using Asp.net. I'm using XML file to write in which is
<?xml version="1.0" encoding="utf-8"?>
<urlset>
</urlset>
and code behind for Article.aspx which have urls
string xmlpath = #"~/data.xml";
var path = Server.MapPath(xmlpath);
XDocument doc = XDocument.Load(path);
XElement root = new XElement("url");
root.Add(new XElement("loc", url));
root.Add(new XElement("lastmod", DateTime.Now.ToString("yyyy-MMdd")));
root.Add(new XElement("lastmod", "daily"));
root.Add(new XElement("priority", "1.0"));
doc.Element("urlset").Add(root);
doc.Save(path);
This code is working good and I get the XML file correctly the problem is Google Search console need me to add xmlns nameSpace to the urlset element so it must be like this:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
</urlset>
When I do add the NameSpace xmlns to the the <urlset> tag I get this error:
object reference not set
I like creating a new XDocument by parsing a string especially when you have namespaces
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">" +
"</urlset>";
XDocument doc = XDocument.Parse(xml);
XElement urlset = doc.Root;
I found answer as "madreflection" mentioned at Microsoft community
code behind:
XNamespace aw = "http://www.sitemaps.org/schemas/sitemap/0.9";
doc.Element(aw + "urlset").Add(root);
and my XML file is
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
</url>
</urlset>

How to add xsi:noNamespaceSchemaLocation to Serializer

I build an XML Document which needs to be validated against a xsd file. Thus I need a reference to the xsd file in the root element of the xml. So far I use this C# Code:
var ser = new XmlSerializer(typeof(myspecialtype));
XmlSerializerNamespaces MainNamespace = new XmlSerializerNamespaces();
MainNamespace.Add("xlink", "http://www.w3.org/1999/xlink");
MainNamespace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
using (XmlWriter w = XmlWriter.Create(#"C:\myxmlfile.xml"))
{
w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"utils/somexsl.xsl\"");
ser.Serialize(w, LeBigObject, HauptNs);
}
The resulting Xml begins like this:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="utils/somexsl.xsl"?>
<caddy-xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlVersion="03.07.00">
but I need this:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="utils/somexsl.xsl"?>
<caddy-xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlVersion="03.07.00" xsi:noNamespaceSchemaLocation="utils/theveryimportant.xsd">
I came across "CreateAttribute" here: Add Namespace to an xml root node c# but I can't put it together with the Serializer. Thank you!
I was pointed to the solution here:
https://social.msdn.microsoft.com/Forums/en-US/e43585c6-181b-4449-8806-b07f82681a2a/how-to-include-xsinonamespaceschemalocation-in-the-xml?forum=asmxandxml
I added this to my class:
[XmlAttribute("noNamespaceSchemaLocation", Namespace = XmlSchema.InstanceNamespace)]
public string attr = "utils/theveryimportant.xsd";
and it works.

How to edit content of a tag in a xml file

Example
<?xml version="1.0" encoding="UTF-8"?>
<Settings>
<Tag1>XXXX</Tag1>
<Tag2>YYYY</Tag2>
<Tag3>true</Tag3>
<Tag4>ZZZZ</Tag4>
</Settings>
I want to edit only the contents of Tag3 without having to create another .xml file
You may edit your XML file like this:
XmlDocument doc = new XmlDocument();
doc.Load("D:\\somefile.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("Settings::Tag3");
myNode.Value = "blabla";
doc.Save("D:\\somefile.xml");

Issue on saving the XML file after editing it

I have an XML file with some data on it..for example
<?xml version="1.0" encoding="utf-8"?>
<CreateAndSendMessageRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.communisis.com/lv">
<CompositionRequest>
<Metadata xmlns="http://lv.com/gi/si/common/CommonTypes">
<PolicyReference>250028766505DN</PolicyReference>
<AccountReference>Test1234</AccountReference>
<QuoteReference>Test3214</QuoteReference>
<OutboundTransactionID>string</OutboundTransactionID>
</Metadata>
Now i want to replace POLICY REFERENCE value with some dummy data. I am able to do that but now i have to save it as a new file with a different file name..
How can i achieve that..
For reference i am giving my code.
XmlDocument doc = new XmlDocument();
doc.Load(filepath);
XmlNodeList node = doc.GetElementsByTagName("PolicyReference");
var item =node.Item(0);
string value = item.FirstChild.Value;
string nevalue = value.Replace(value, "Test123");
doc.DocumentElement.;
doc.Save(#"C:\Test\file.xml");
The xml wasn't valid.
Anyway, this is how to make it work:
Xml file:
<?xml version="1.0" encoding="UTF-8"?>
<CreateAndSendMessageRequest>
<CompositionRequest>
<Metadata xmlns="http://lv.com/gi/si/common/CommonTypes">
<PolicyReference>250028766505DN</PolicyReference>
<AccountReference>Test1234</AccountReference>
<QuoteReference>Test3214</QuoteReference>
<OutboundTransactionID>string</OutboundTransactionID>
</Metadata>
</CompositionRequest>
</CreateAndSendMessageRequest>
Code:
XmlDocument doc = new XmlDocument();
doc.Load("bho.xml");
XmlNodeList node = doc.GetElementsByTagName("PolicyReference");
node[0].InnerText = "Test123";
doc.Save("file.xml");
Result xml:
<?xml version="1.0" encoding="UTF-8"?>
<CreateAndSendMessageRequest>
<CompositionRequest>
<Metadata xmlns="http://lv.com/gi/si/common/CommonTypes">
<PolicyReference>Test123</PolicyReference>
<AccountReference>Test1234</AccountReference>
<QuoteReference>Test3214</QuoteReference>
<OutboundTransactionID>string</OutboundTransactionID>
</Metadata>
</CompositionRequest>
</CreateAndSendMessageRequest>
Hope it helps you ^^

Add XDeclaration to XDocument after it's constructed

I have an XmlSerializer which I use to Serialize an object to an XDocument.
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, object);
}
After this is done, I want to add a XDeclaration:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
I construct this XDeclaration as described below:
var decl = new XDeclaration("1.0", "UTF-8", "no");
However, when I try to add this XDeclartion to my XDocument, I get the following error:
System.ArgumentException : Non white space characters cannot be added to content.
I searched Google for some time but all I've found is adding the XDeclaration to the constructor of the XDocument which in my case (when filling it with a XmlWriter) is not acceptable.
Use property XDocument.Declaration
EDIT:
Sample code:
var xmlSerializer = new XmlSerializer(typeof(int));
var doc = new XDocument();
var decl = new XDeclaration("1.0", "utf-8", "no");
doc.Declaration = decl;
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, 1);
}
doc.Save(File.Create("x.xml"));
This code produced following output:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<int>1</int>

Categories