這不是對如何告訴XmlSerialiser忽略名稱空間而是解決方法的問題的回答。在序列化之前,可以使用xslt變換從XML中去除名稱空間。
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
一對夫婦的擴展方法作爲助手對於這一點,將是一個有點棘手,讓他們所有的也許,但我會嘗試:
/// <summary>
/// Transforms the xmldocument to remove all namespaces using xslt
/// http://stackoverflow.com/questions/987135/how-to-remove-all-namespaces-from-xml-with-c
/// http://msdn.microsoft.com/en-us/library/42d26t30.aspx
/// </summary>
/// <param name="xmlDocument"></param>
/// <param name="indent"></param>
public static XmlDocument RemoveXmlNameSpaces(this XmlDocument xmlDocument, bool indent = true)
{
return xmlDocument.ApplyXsltTransform(Properties.Resources.RemoveNamespaces, indent);
}
public static XmlDocument ApplyXsltTransform(this XmlDocument xmlDocument, string xsltString,bool indent= true)
{
var xslCompiledTransform = new XslCompiledTransform();
Encoding encoding;
if (xmlDocument.GetEncoding() == null)
{
encoding = DefaultEncoding;
}
else
{
encoding = Encoding.GetEncoding(xmlDocument.GetXmlDeclaration().Encoding);
}
using (var xmlTextReader = xsltString.GetXmlTextReader())
{
xslCompiledTransform.Load(xmlTextReader);
}
XPathDocument xPathDocument = null;
using (XmlTextReader xmlTextReader = xmlDocument.OuterXml.GetXmlTextReader())
{
xPathDocument = new XPathDocument(xmlTextReader);
}
using (var memoryStream = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings()
{
Encoding = encoding,
Indent = indent
}))
{
xslCompiledTransform.Transform(xPathDocument, xmlWriter);
}
memoryStream.Position = 0;
using (var streamReader = new StreamReader(memoryStream, encoding))
{
string readToEnd = streamReader.ReadToEnd();
return readToEnd.ToXmlDocument();
}
}
}
public static Encoding GetEncoding(this XmlDocument xmlDocument)
{
XmlDeclaration xmlDeclaration = xmlDocument.GetXmlDeclaration();
if (xmlDeclaration == null)
return null;
return Encoding.GetEncoding(xmlDeclaration.Encoding);
}
public static XmlDeclaration GetXmlDeclaration(this XmlDocument xmlDocument)
{
XmlDeclaration xmlDeclaration = null;
if (xmlDocument.HasChildNodes)
xmlDeclaration = xmlDocument.FirstChild as XmlDeclaration;
return xmlDeclaration;
}
public static XmlTextReader GetXmlTextReader(this string xml)
{
return new XmlTextReader(new StringReader(xml));
}
您是否考慮過首先加載XML以獲取命名空間,以便將其傳遞給XmlSerializer? –
@StevenDoggart是的,但我想知道在開始解決此問題之前是否有更合適的方法來完成此操作。這看起來很愚蠢,你不能忽略命名空間而不會發生異常:S – user1698428
是的,這是一個非常好的問題,我很好奇,如果有答案的話。 –