![](/img/trans.png)
[英]How do you remove xmlns from elements when generating XML with LINQ?
[英]Remove xmlns attribute from elements when generating XML with LINQ?
我有關於生成sitemap.xml
的問題
我的創作者代碼如下:
XNamespace xmlns = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");
XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace schemaLocation = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
XElement urlset = new XElement(xmlns+"urlset",
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", schemaLocation));
urlset.Add(new XElement("url"));
此代碼生成xml文件,但生成的sitemap.xml
url元素包括xmlns=""
屬性。
<urlset xmlns="..." ><url xmlns=""/> </urlset>
所有<url>
元素都包含xmlns = ""
屬性。
我該如何解決?
我認為W3 Org可以比我更好地總結名稱空間,您對'url'節點上方的所有節點和屬性都有合格的名稱空間。 當您添加urlset.Add(new XElement("url"));
應該如何確定其所在的名稱空間?
我建議您嘗試一下,看看它如何為您工作:
static void Main ( string [] args )
{
XNamespace xmlns = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");
XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace schemaLocation = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
XElement urlset = new XElement(xmlns+"urlset",
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", schemaLocation));
urlset.Add(new XElement(xmlns+"url")); // NB> We are qualifying the node
var s = urlset.ToString( );
Console.ReadKey( );
}
試試這個代碼
XmlDocument stripDocumentNamespace(XmlDocument oldDom)
{
XmlDocument newDom = new XmlDocument();
newDom.LoadXml(Regex.Replace(oldDom.OuterXml,
@"(xmlns:?[^=]*=[""][^""]*[""])", "",
RegexOptions.IgnoreCase | RegexOptions.Multiline));
return newDom;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.