我正在尝试使用 XMLSerializer 在少数元素中的一个元素中生成带有命名空间前缀的 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 的每个标记中。
请帮忙。