如何给根元素添加xmlns属性?

问题描述 投票:0回答:3

我必须像下面这样编写xml文件

<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Status>Enabled</Status>
</VersioningConfiguration>

请任何人帮我写上面的内容。

c# xml
3个回答
1
投票

LINQ to XML 使这变得很简单 - 您只需指定元素的命名空间,它将自动包含

xmlns="..."
。您可以给它一个别名,但这稍微困难一些。要生成您所显示的确切文档,您只需要:

XNamespace ns = "http://s3.amazonaws.com/doc/2006-03-01/";
var doc = new XDocument(
    new XElement(ns + "VersioningConfiguration",
       new XElement(ns + "Status", "Enabled")));
Console.WriteLine(doc);

LINQ to XML 是迄今为止我用过的最好的 XML API,特别是在它对命名空间的处理方面。只是对

XmlDocument
说不:)


0
投票
 XNamespace Name = "http://s3.amazonaws.com/doc/2006-03-01/";
 XDocument doc=new XDocument();
 XElement X1=new XElement(Name+"VersioningConfiguration","" );
 XElement X2=new XElement(Name+"Status","Enabled");
 X1.Add(X2);
 doc.Add(X1);

0
投票

创建X文档

以下是如何正确创建

XDocument

XNamespace aws = "http://s3.amazonaws.com/doc/2006-03-01/";

XDocument doc = new XDocument(
    // add the XML declaration (optional)
    new XDeclaration("1.0", "utf-8", null),

    // add the root element
    // prefer to place namespace imports here
    new XElement(aws + "VersioningConfiguration",

       // creates an acronym for the namespace
       new XAttribute(XNamespace.Xmlns + "aws", aws),

       // IMPORTANT: remember to add the namespace to all elements and attributes
       new XElement(aws + "Status", "Enabled")
    )
);

// consider SaveOptions as required
string xml = doc.ToString(SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);

Console.WriteLine(xml);

结果(带格式)将是:

<aws:VersioningConfiguration xmlns:aws="http://s3.amazonaws.com/doc/2006-03-01/">
  <aws:Status>Enabled</aws:Status>
</aws:VersioningConfiguration>

有关文化相关格式的注意事项

请注意,

XElement
XAttribute
将调用子元素上的
.ToString(CultureInfo.CurrentCulture)
方法。当不同的格式规则应用于
double
float
时,这可能会出现问题。
bool
等等..

我的建议是始终显式调用

.ToString(CultureInfo.InvariantCulture)
以及可能的
.ToLower()
方法以防止格式问题。另请记住在解析 XML 文件时使用适当的区域性。

使用XmlWriter的注意事项

如果要将 XML 写入文件,请考虑以下事项:

var settings = new XmlWriterSettings
{
    Encoding = Encoding.UTF8,
    Indent = true
};

using (var writer = XmlWriter.Create("path/to/file.xml", settings))
{
    doc.Save(writer);
}

注意

XmlWriter.Create
也接受
Stream
对象,即。如果你想写信给

  • 文本流
  • 文件流
  • 内存流
  • 字符串生成器
© www.soinside.com 2019 - 2024. All rights reserved.