简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM