我正嘗試使用XMLSerializer在少數元素中的一個元素中生成名稱空間前綴的XML。只需要在一個XML元素中添加XML名稱空間前綴
下面是代碼 -
var commRemision = new Contracts.Dtos.Remision();
Transformer transformedRequest = new Transformer();
commRemision = transformedRequest.TransformRequest(dgRemision);
public const string ElementNamespace = "http://www.buzonfiscal.com/ns/xsd/bf/remision/52";
XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, ElementNamespace); ///remove default namespaces
var serializer = new XmlSerializer(commRemision.GetType(), ElementNamespace);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string
settings.Indent = true;
settings.OmitXmlDeclaration = false;
using (StringWriter textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, commRemision, xmlNamespace);
}
}
和階級結構 -
public class Remision
{
[XmlElement]
public InfoBasica InfoBasica { get; set; }
[XmlElement]
public Addenda Addenda { get; set; }
}
public class InfoBasica
{
[XmlAttribute]
public int folio { get; set; }
}
[XmlRoot("Addenda", Namespace = Addenda.ElementNamespace)]
public class Addenda
{
public const string ElementNamespace = "http://www.buzonfiscal.com/ns/addenda/bf/2";
[XmlElement(Namespace = ElementNamespace)]
public List<AddendaBuzonFiscal> AddendaBuzonFiscal { get;set;}
}
public class AddendaBuzonFiscal
{
[XmlElement(ElementName = "Emisor")]
public AddendaEmisor Emisor { get; set; }
[XmlElement]
public AddendaReceptor Receptor { get; set; }
[XmlElement]
public TipoDocumento TipoDocumento { get; set; }
}
現在我需要我的XML是這樣的 -
<Remision version="5.2" xmlns="http://www.buzonfiscal.com/ns/xsd/bf/remision/52">
<InfoBasica folio="10240" />
<Addenda>
<ns:AddendaBuzonFiscal version="2.0" xmlns:ns="http://www.buzonfiscal.com/ns/addenda/bf/2">
<ns:Emisor telefono="8787826600" />
<ns:Receptor telefono="1234567" />
<ns:TipoDocumento nombreCorto="FAC" />
</ns:AddendaBuzonFiscal>
</Addenda>
</Remision>
但無法添加ns元素中的前綴。我所能夠產生是這樣的 -
<Remision version="5.2" xmlns="http://www.buzonfiscal.com/ns/xsd/bf/remision/52">
<InfoBasica folio="10240" />
<Addenda>
<AddendaBuzonFiscal version="2.0" xmlns:ns="http://www.buzonfiscal.com/ns/addenda/bf/2">
<Emisor telefono="8787826600" />
<Receptor telefono="1234567" />
<TipoDocumento nombreCorto="FAC" />
</AddendaBuzonFiscal>
</Addenda>
</Remision>
請注意,我需要空間前綴只在AddendaBuzonFiscal標籤不在XML的每一個標籤。
請幫忙。
你的第二位o f XML不是*您將生成的內容 - 它將是'AddendaBuzonFiscal'中的'xmlns =「..」',而不是'xmlns:ns =「..」'。鑑於此,這兩者在語義上是相同的。你需要提供原因,爲什麼這不被接受。 –