C# 如何显示正确的xml格式

C# 如何显示正确的xml格式,c#,xml,C#,Xml,我正在尝试创建前缀为g的xml文档: c# 相反,它显示为: ..<contacts> <contact> <name xmlns="g:"> ... 。。 ... 您的代码对我来说运行良好(输出为): 输出: <Contacts xmlns:g="http://somewhere.com"> <Contact> <g:Name>Patrick Hines</g:Name> &l

我正在尝试创建前缀为g的xml文档:

c#

相反,它显示为:

..<contacts>
  <contact>
    <name xmlns="g:">
...
。。
...

您的代码对我来说运行良好(输出为):

输出:

<Contacts xmlns:g="http://somewhere.com">
  <Contact>
    <g:Name>Patrick Hines</g:Name>
    <Phone>206-555-0144</Phone>
    <Address>
      <street>this street</street>
    </Address>
  </Contact>
</Contacts>

帕特里克·海因斯
206-555-0144
这条街

XDocument
位于
System.Xml.Linq
命名空间中。因此,在代码文件的顶部添加:

using System.Xml.Linq;
然后,您可以通过以下方式将数据写入文件:

XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
            new System.Xml.Linq.XElement("Contacts"),
            new XElement("Contact",
            new XElement("Name", c.FirstOrDefault().DisplayName),
            new XElement("PhoneNumber", c.FirstOrDefault().PhoneNumber.ToString()),
            new XElement("Email", "abc@abc.com"));
doc.Save(...);
XNamespace g = "http://somewhere.com";
XElement contacts =
    new XElement("Contacts", new XAttribute(XNamespace.Xmlns + "g", g),
        new XElement("Contact",
            new XElement( g+"Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144"),
            new XElement("Address",
                new XElement("street","this street"))               

        )
    );
<Contacts xmlns:g="http://somewhere.com">
  <Contact>
    <g:Name>Patrick Hines</g:Name>
    <Phone>206-555-0144</Phone>
    <Address>
      <street>this street</street>
    </Address>
  </Contact>
</Contacts>
using System.Xml.Linq;
XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
            new System.Xml.Linq.XElement("Contacts"),
            new XElement("Contact",
            new XElement("Name", c.FirstOrDefault().DisplayName),
            new XElement("PhoneNumber", c.FirstOrDefault().PhoneNumber.ToString()),
            new XElement("Email", "abc@abc.com"));
doc.Save(...);