user9470241
user9470241

Reputation:

Xml Root.add value with Special Character( :)

I have an XML file which is

<?xml version="1.0" encoding="utf-8"?>
<urlset >

</urlset>

I'm trying to add an XElement with special characters (:) code behind

string xmlpath = @"~/myxml.xml";
string path = Server.MapPath(xmlpath);
string title="SomeString"
XDocument doc = XDocument.Load(path);
XElement root = new XElement("url");
root.Add(new XElement("Video:title", "title"));//here is the problem i have Special char (:) which not allowed
doc.Element("urlset").Add(root);

also i can't use &qoute; becuse it's contniue special char & Please i need help if any one can help i would be thankful thanks a lot for your time guys and thank a lot for giving time to read my queation

Upvotes: 0

Views: 538

Answers (1)

Trevor
Trevor

Reputation: 8004

I'm trying to add an XElement with special characters (:) code behind

Try using a XmlDocument which will allow creating an XmlElement with specified name and namespace.

 string xmlpath = @"~/myxml.xml";
 string path = Server.MapPath(xmlpath);
 XmlDocument doc = new XmlDocument();

 doc.Load(path);
 var mainRoot = doc.DocumentElement; //urlset element
 var urlRoot = doc.CreateElement("url"); //create url element
 urlRoot.AppendChild(doc.CreateElement("Video:title","title")); //add element to the url element
 mainRoot.AppendChild(urlRoot); // add this new element to the main root of urlset

Example Output:

<?xml version="1.0" encoding="utf-8"?>
<urlset>
  <url>
    <Video:title xmlns:Video="title" />
  </url>
</urlset>

Or if you just want a Video node with namespace of title...

 urlRoot.AppendChild(doc.CreateElement("Video","title"));

The output of this above:

<?xml version="1.0" encoding="utf-8"?>
<urlset>
  <url>
    <Video xmlns="title"/>
  </url>
</urlset>

Please let me know if this isn't your expected output.

Upvotes: 1

Related Questions