我的XML是:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://localhost:2511/SF/sitemap_1.xml</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
<sitemap>
<loc>http://localhost:2511/SF/sitemap_2.xml</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
</urlset>
我想在此xml中添加新的<sitemap>
节点。
我试试:
public void LoadXML()
{
string sSiteMapFilePath = HttpRuntime.AppDomainAppPath + "sitemap_index.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpRuntime.AppDomainAppPath + "sitemap_index.xml");
//XmlDocumentFragment docFrag = xmlDoc.CreateDocumentFragment();
XmlNode node=GenerateIndexNode(Page.Request.Url.Scheme + "://" + Request.Url.Authority + "Test" + "/sitemap_" + "4" + ".xml");
//docFrag.InnerXml = node.ToString();
XmlNode childNode = xmlDoc.DocumentElement;
childNode.InsertAfter(node, childNode.LastChild);
xmlDoc.Save(sSiteMapFilePath);
}
public XmlNode GenerateIndexNode(string Loc)
{
XmlDocument xd = new XmlDocument();
xd.Load(HttpRuntime.AppDomainAppPath + "sitemap_index.xml");
XmlElement nodeSite = xd.CreateElement("sitemap");
XmlElement nodeLoc = xd.CreateElement("loc");
nodeLoc.InnerText = Loc;
XmlElement nodeMode = xd.CreateElement("lastmod");
nodeMode.InnerText = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss+00:00");
nodeSite.AppendChild(nodeLoc);
nodeSite.AppendChild(nodeMode);
return nodeSite;
}
Desire Out put是:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://localhost:2511/SF/sitemap_1.xml</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
<sitemap>
<loc>http://localhost:2511/SF/sitemap_2.xml</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
<sitemap>
<loc>New URL</loc>
<lastmod>2013-11-11T04:17:57+00:00</lastmod>
</sitemap>
</urlset>
但我收到了错误:
The node to be inserted is from a different document context.
有些事情出错了。我缺少一些可以理解的东西。谢谢你的帮助。
答案 0 :(得分:0)
您已经在LoadXML()
中加载了sitemap xml文件,无需在GenerateIndexNode()
中重新加载此文件,而只需将加载文件的引用传递给此函数:
public XmlNode GenerateIndexNode(XmlDocument xd)
{
XmlElement nodeSite = xd.CreateElement("sitemap");
XmlElement nodeLoc = xd.CreateElement("loc");
nodeLoc.InnerText = Loc;
XmlElement nodeMode = xd.CreateElement("lastmod");
nodeMode.InnerText = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss+00:00");
nodeSite.AppendChild(nodeLoc);
nodeSite.AppendChild(nodeMode);
return nodeSite;
}
可以这样打电话:
public void LoadXML()
{
string sSiteMapFilePath = HttpRuntime.AppDomainAppPath + "sitemap_index.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpRuntime.AppDomainAppPath + "sitemap_index.xml");
XmlNode node=GenerateIndexNode(xmlDoc);
XmlNode childNode = xmlDoc.DocumentElement;
childNode.InsertAfter(node, childNode.LastChild);
xmlDoc.Save(sSiteMapFilePath);
}