在XML中编写命名空间

3
我需要使用C#类(XmlDocument或XDocument)生成一个XML文件,根元素如下所示:
<ns1:ConsultaSeqRps xmlns:ns1="http://localhost:8080/WsNFe2/lote" 
    xmlns:tipos="http://localhost:8080/WsNFe2/tp" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://localhost:8080/WsNFe2/lote http://localhost:8080/WsNFe2/xsd/ConsultaSeqRps.xsd">

我尝试过使用setAttribute和XmlNamespaceManager的不同替代方法,但都没有成功。


1
请展示您使用的代码,这样我们就可以告诉您哪里出了问题。 - John Saunders
我已经编辑了你的标题。请参考“问题的标题应该包含“标签”吗?”,在那里达成共识是“不应该”。 - John Saunders
看看这个能否帮到你 - 可能与此无关 - http://stackoverflow.com/questions/8450860/why-does-net-xml-append-an-xlmns-attribute-to-xmlelements-i-add-to-a-document - jdphenix
2个回答

3

这很简单,除了使用XAttribute添加命名空间可能有些棘手:

XNamespace ns1 = "http://localhost:8080/WsNFe2/lote";
XNamespace tipos = "http://localhost:8080/WsNFe2/tp";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

var doc = new XElement(ns1 + "ConsultaSeqRps",
    new XAttribute(XNamespace.Xmlns + "ns1", ns1), 
    new XAttribute(XNamespace.Xmlns + "tipos", tipos), 
    new XAttribute(XNamespace.Xmlns + "xsi", xsi),
    new XAttribute(xsi + "schemaLocation", 
      "http://localhost:8080/WsNFe2/lote http://localhost:8080/WsNFe2/xsd/ConsultaSeqRps.xsd")
    );

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接