0

我正在尝试创建一个带有前缀 g 的 xml 文档:

C#

 static void Main(string[] args)
        {
            XNamespace g = "g:";
            XElement contacts =
    new XElement("Contacts",
        new XElement("Contact",
            new XElement( g+"Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144"),
            new XElement("Address",
                new XElement("street","this street"))               

        )
    );
            Console.WriteLine(contacts);
        }

相反,它显示为:

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

3 回答 3

1
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>
于 2013-08-27T05:32:36.257 回答
0

XDocumentSystem.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(...);
于 2013-08-27T05:42:30.883 回答
0

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

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

如果您仍然无法获得正确的输出,那么您可以试试这个:

new XDocument(
    new XElement("Contacts", 
        new XElement("Contact", 
             new XElement("Name", "Patrick Hines"),
             new XElement("Phone", "206-555-0144"),
             new XElement("Address",  
                        new XElement("street","this street"))
        )    
    )
).Save("foo.xml");
于 2013-08-27T05:27:38.923 回答