使用XmlWriter添加属性

时间:2012-11-30 15:26:12

标签: c# xml xmlwriter

我正在尝试使用XmlWriter将以下属性添加到节点,但似乎没有任何效果,是否有人有任何想法?

<news:news>

我正在努力实现以下目标:

 <url>
    <loc>http://www.example.org/business/article55.html</loc>
    <news:news>
      <news:publication>
        <news:name>The Example Times</news:name>
        <news:language>en</news:language>
      </news:publication>
      <news:access>Subscription</news:access>
      <news:genres>PressRelease, Blog</news:genres>
      <news:publication_date>2008-12-23</news:publication_date>
      <news:title>Companies A, B in Merger Talks</news:title>
      <news:keywords>business, merger, acquisition, A, B</news:keywords>
      <news:stock_tickers>NASDAQ:A, NASDAQ:B</news:stock_tickers>
    </news:news>
  </url>

由于

2 个答案:

答案 0 :(得分:1)

请查看以下链接,了解如何使用XmlWriter

处理命名空间

Namespace Handling in the XmlWriter

您可以使用WriteAttributeString方法手动写出命名空间声明,然后使用WriteStartElement(String, String)重载将未来元素与该命名空间相关联,如此

writer.WriteStartElement("root");
writer.WriteAttributeString("xmlns", "x", null, "urn:1");
writer.WriteStartElement("item", "urn:1");
writer.WriteEndElement();
writer.WriteStartElement("item", "urn:1");
writer.WriteEndElement();
writer.WriteEndElement();

答案 1 :(得分:0)

    using System;
    using System.Xml;

    class Program
    {
        static void Main(string[] args)
        {
            XmlWriter writer = new XmlTextWriter(Console.Out);
            writer.WriteStartElement("root");
            writer.WriteAttributeString("news", "http://www.stackoverflow.com");
            writer.WriteStartElement("news:news");
            writer.WriteStartElement("news:publication");
            writer.WriteElementString("news:name", "The Example Times");
            writer.WriteElementString("news:language", "en");
            // etc
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();
            Console.ReadKey(true);
        }
    }