Add Nested XML Node to xml File using Asp.net and C# - c#

I Want add some url to xml file on my website using C#.
I have already create a XML file on website Root.
The content of xml file is :
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>http://www.structure.com/Structure.aspx?id=1</loc>
</url>
</urlset>
Now I want add new <url> Node with <loc> node to xml file and I want xml content changes like
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>http://www.structure.com/Structure.aspx?id=1</loc>
</url>
<url>
<loc>http://www.structure.com/Structure.aspx?id=2</loc>
</url>
</urlset>
I try made a function that get url string from web form and it's triggers on asp:Button click
protected void Button1_Click(object sender, EventArgs e)
{
insertSiteMap("http://www.structure.com/Structure.aspx?id=2");
}
And the function is:
private void insertSiteMap(string pageurl)
{
//Load XML Schema
System.Xml.XmlDocument originalXml = new System.Xml.XmlDocument();
originalXml.Load(Server.MapPath("../sitemap.xml"));
XmlElement URL = originalXml.CreateElement("url");
XmlElement LOC = originalXml.CreateElement("loc");
XmlText LOCText = originalXml.CreateTextNode(pageurl);
LOC.AppendChild(LOCText);
URL.AppendChild(LOC);
XmlNode newUrl = originalXml.GetElementsByTagName("url")[0];
originalXml.DocumentElement.PrependChild(newUrl);
originalXml.Save(Server.MapPath("../sitemap.xml"));
}
I don't have any error and visual studio message me xml file has been modified but when I open the file there is no any changes on xml file :(.
am I did wrong any where?

Once you have created the new element with your variable URL, you need to insert with e.g. originalXml.DocumentElement.AppendChild(URL);.
However, take note that in your original XML you use a namespace while your C# code creates the new XmlElements in no namespace, so you need to fix the element creation as well, e.g.
XmlElement url = originalXml.CreateElement("url", originalXml.DocumentElement.NamespaceURI);
XmlElement loc = originalXml.CreateElement("loc", originalXml.DocumentElement.NamespaceURI);
loc.InnerText = pageurl;
url.AppendChild(loc);
originalXml.DocumentElement.AppendChild(url);

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 ^^

Tag contents adding to XML file in c# window application

i have an xml file sitemap.xml as shown below ..i need to add one more
tag here after <Name> tag..Means After <Name>test</Name> tag here
i need to add destination tag like <Destination>NY</Destination>
.Can we add contents to xml through a textbox by pressing a button
control without manually doing
this is xml file sitemap.xml
<?xml version="1.0" encoding="utf-8" ?>
<ObjectClass>
<Image>00000000-0000-0000-0000-000000000000</Image>
<Description />
<Name>test</Name>
<DefaultApp>00000000-0000-0000-0000-000000000000</DefaultApp>
<ID>464930eb-e518-4d0c-b80b-184c97c7dd27</ID>
<ParentClassID>00000000-0000-0000-0000-000000000002</ParentClassID>
<DynamicPopulation>false</DynamicPopulation>
<TimeoutPeriod>0</TimeoutPeriod>
<Persist>false</Persist>
<ClassVersion>1</ClassVersion>
<Reinitialize>false</Reinitialize>
</ObjectClass>
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlElement elt = doc.CreateElement("Destination");
elt.InnerText = "NY";
doc.DocumentElement.AppendChild(elt);
doc.Save(fileName);
To delete an element :
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement elt = doc.DocumentElement.SelectSingleNode("Destination") as XmlElement;
if (elt != null)
doc.DocumentElement.RemoveChild(elt);
doc.Save();

Categories