如何显示正确的xml格式
本文关键字:xml 格式 何显示 显示 | 更新日期: 2023-09-27 18:29:11
我正在尝试创建一个前缀为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:">
...
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>
您的代码对我来说运行良好(输出为):
<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");
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(...);