从c#linq到xml显示的元标记<

时间:2013-10-21 22:01:04

标签: c# asp.net xml

    XmlDocument doc = new XmlDocument();
    XDocument XMLDoc = XDocument.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/google_meta2.xml"));
    string id = "2"; // id to be selected

    XElement Contact = (from xml2 in XMLDoc.Descendants("Keywords")
                        where xml2.Element("ID").Value == id
                        select xml2).FirstOrDefault();

    string key = HttpUtility.HtmlDecode(Contact.Element("name").ToString()); 

     /* not works :
    string cleanedString = key ;

    cleanedString = cleanedString.Replace("<","&lt;");      // No code
    cleanedString = cleanedString.Replace(">", "&gt;");
    cleanedString = cleanedString.Replace("&", "&amp;");    // No query string breaks
     */

    HtmlMeta meta = new HtmlMeta();
    meta.Name = "keywords";
    meta.Content = key;
    MetaPlaceHolder.Controls.Add(meta);

XML

<?xml version="1.0" encoding="utf-8"?>
<Google>
  <Keywords>
    <ID>2</ID>
      <name>bla</name>
  </Keywords>
</Google>

输出

<meta name="keywords" content="&lt;name>bla&lt;/name>" /></head>

我如何删除&amp; lt,或者有更好的方法呢?

1 个答案:

答案 0 :(得分:4)

尝试从XElement中检索属性,而不是使用HtmlDecode:

XElement contact = (from xml2 in XMLDoc.Descendants("Keywords")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

HtmlMeta meta = new HtmlMeta();
meta.Name = "keywords";
meta.Content = contact.Attribute("name").Value;