C# 在XDocument中设置根命名空间前缀
我目前有:C# 在XDocument中设置根命名空间前缀,c#,xml,xsd,linq-to-xml,xelement,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(xs
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
读取ns1:BaseReport
?以下代码将为您提供所需的输出。关键是在名称之前添加定义的名称空间,并让.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)));
您能否将变量
xsi
、schemaloc
和xmlns
的赋值添加到您的代码示例中?在做了额外的研究之后,我认为您不能在根元素中使用名称空间。名称空间被定义为根元素的属性,并且对于根元素本身是未定义的。您可以阅读更多内容。但是,当我使用XMLSpy之类的东西从XSD生成示例xml时,它使用“ns1:BaseReport”作为头标记…并且它没有在更高级别声明ns1
命名空间?它在哪里声明这个名称空间?XMLSpy生成器生成一个xml,其xml头与我在代码中要做的相同,我只是不知道如何获取代码中的“ns1:BaseReport”部分,以便正确验证。啊,是的,我从您发送的上一个链接中得到了这个。[页面没有刷新,德普]非常感谢@用户2073374没问题,我很高兴能帮上忙。
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)));