开发者

Work with XML file

开发者 https://www.devze.com 2023-01-24 22:20 出处:网络
I have a sitemap file for search engines: <?xml version=\"1.0\" encoding=\"utf-8\"?> <urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchem

I have a sitemap file for search engines:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitema开发者_开发百科p/0.9             http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://site.com/</loc>
  </url>
  <url>
    <loc>http://site.com/about</loc>
  </url>
  <url>
    <loc>http://site.com/contacts</loc>
  </url>
  <url>
    <loc>http://site.com/articles/article1.html</loc>
  </url>
  <url>
    <loc>http://site.com/users/123</loc>
  </url>
</urlset>

How to insert a new node?

When I use xDoc.Element("url") or xDoc.Element("urlset") or xDoc.Element("xml") or Doc.Elements(...) I get null always. It's very strange.


The code below shows how to navigate within the xml and how to insert a new node

XDocument xDoc = XDocument.Load("sitemap.xml");
XNamespace ns = xDoc.Root.Name.Namespace;

// Navigation within the xml 
XElement urlset = xDoc.Element(ns + "urlset");
Console.WriteLine(urlset.Name.LocalName);    // -> "urlset"

IEnumerable<XElement> urls = urlset.Elements(ns + "url");

foreach (var url in urls)
{
    XElement loc = url.Element(ns + "loc");
    Console.WriteLine(loc.Value);    // -> "http://site.com/", ...                
}

// Inserting a new node under "urlset" node
urlset.Add(
    new XElement(ns + "url",
        new XElement(ns + "loc",
            "http://site.com//questions/4183526")));
0

精彩评论

暂无评论...
验证码 换一张
取 消