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

本文关键字:显示 linq xml | 更新日期: 2023-09-27 18:36:15

    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>

如何删除 <,或者有更好的方法可以做到这一点?

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

尝试从 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;