我从 2 个不同的 XSD 中获得了 2 个类,其中一个是它的子节点,根类有一个子节点的属性(xmlelement 数组),我需要子节点有不同的前缀。这是我的代码:
var xml = //this is the root xml
var nom = //this is the child node
var stream = new MemoryStream();
var xmlSerializeNomina = new XmlSerializer(typeof(ChildClass));
var xmlNameSpaceNom = new XmlSerializerNamespaces();
//Here add namespace because i need the prefix in child node
xmlNameSpaceNom.Add("childPrefix", "http://www.url.com/child");
var doc = new XmlDocument();
using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
xmlSerializeNomina.Serialize(writer, nom, xmlNameSpaceNom);
stream.Seek(0, SeekOrigin.Begin);
doc.Load(stream);
}
//This is the xmlelement array property
xml.Complemento.Any = new XmlElement[] { doc.ImportNode(doc.DocumentElement, true) as XmlElement };
然后我序列化根:
var xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("rootPrefix", "http://www.url.com/foo");
xmlNameSpace.Add("nsPrefix", "http://www.url.com/foo");
xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
var urls += "http://www.url.com/foo http://www.url.com/root.xsd http://www.url.com/url_child http://www.url.com/url_child/child.xsd";
//Here add then child namespace because i need it in root node
xmlNameSpace.Add("childPrefix", "http://www.url.com/child");
xmlNameSpace.Add("schemaLocation", urls);
var xmlSerializeFactura = new XmlSerializer(typeof(RootClass));
using (var xmlTextWriter = new XmlTextWriter("pathAndName.xml", Encoding.UTF8))
{
xmlTextWriter.Formatting = Formatting.Indented;
xmlSerializeFactura.Serialize(xmlTextWriter, xml, xmlNameSpace);
}
XML 文件是以正确的格式创建的,但是子根具有命名空间,我不需要它,只在根节点中。
<?xml version="1.0" encoding="utf-8"?>
<rootPrefix:Comprobante xmlns:schemaLocation="http://www.url.com/foo http://www.url.com/root.xsd http://www.url.com/child http://www.url.com/child/child.xsd" xmlns:nsPrefix="http://www.url.com/foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.url.com/foo http://www.url.com/root.xsd" xmlns:rootPrefix="http://www.url.com/foo">
<rootPrefix:tags>
Some more tags...
</rootPrefix:tags
<rootPrefix:Complemento>
'<!--' in this part is added the namespace, i don't need it here because i have already on root tag but if I don't add it this child tag haven't prefix '-->'
<childPrefix:Tag xmlns:childPrefix="http://www.url.com/child">
Some childs tags..
</childPrefix:Tag>
</rootPrefix:Complemento>
</rootPrefix:Comprobante>