在XDocument中设置根命名空间前缀

时间:2013-02-20 18:05:03

标签: c# xml xsd linq-to-xml xelement

我目前有:

XNamespace xmlns = "XSDName";<br>
XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";<br>
XNamespace schemaloc = @"XSDName XSDName.xsd";
XDocument xdoc = new XDocument(
    new XElement("BaseReport",
    new XAttribute(xsi + "schemaLocation", schemaloc),
    new XAttribute(XNamespace.Xmlns+"ns1", xmlns),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi));

这给了我:

BaseReport xsi:schemaLocation="XSDName XSDName .xsd" xmlns:ns1="XSDName" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

我如何BaseReport阅读ns1:BaseReport

1 个答案:

答案 0 :(得分:3)

以下代码将为您提供所需的输出。关键是在名称之前添加已定义的命名空间,并让.NET找出正确的前缀。

XNamespace xmlns = "XSDName";
XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";
XNamespace schemaloc = @"XSDName XSDName.xsd";
XDocument xdoc = new XDocument(
    new XElement(xmlns + "BaseReport",
    new XAttribute(xsi + "schemaLocation", schemaloc),
    new XAttribute(XNamespace.Xmlns + "ns1", xmlns),
    new XAttribute(XNamespace.Xmlns + "xsi", xsi)));