C #: Como remover informações namespace de elementos XML
-
03-07-2019 - |
Pergunta
Como posso remover os "xmlns: ..."? Informações namespace de cada elemento XML em C #
Solução
resposta de advertência do ZombieSheep não obstante, a minha solução é lavar o xml com uma transformação XSLT para fazer isso.
wash.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8"/>
<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>
Outras dicas
A partir daqui http://simoncropp.com/working-around-xml-namespaces
var xDocument = XDocument.Parse(
@"<root>
<f:table xmlns:f=""http://www.w3schools.com/furniture"">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>");
xDocument.StripNamespace();
var tables = xDocument.Descendants("table");
public static class XmlExtensions
{
public static void StripNamespace(this XDocument document)
{
if (document.Root == null)
{
return;
}
foreach (var element in document.Root.DescendantsAndSelf())
{
element.Name = element.Name.LocalName;
element.ReplaceAttributes(GetAttributes(element));
}
}
static IEnumerable GetAttributes(XElement xElement)
{
return xElement.Attributes()
.Where(x => !x.IsNamespaceDeclaration)
.Select(x => new XAttribute(x.Name.LocalName, x.Value));
}
}
Eu tive um problema semelhante (a necessidade de remover um atributo namespace de um elemento particular, em seguida, retornar o XML como um XmlDocument
para BizTalk), mas uma solução bizarra.
Antes de carregar a string XML para o objeto XmlDocument
, eu fiz uma substituição de texto para remover o atributo namespace ofender. Parecia errado no primeiro como eu acabei com XML que não poderia ser analisado pelo "XML Visualizer" no Visual Studio. Isto é o que inicialmente colocou-me fora dessa abordagem.
No entanto, o texto ainda pode ser carregado no XmlDocument
e eu poderia saída para BizTalk bem.
Note também que antes, eu bati um beco sem saída ao tentar usar childNode.Attributes.RemoveAll()
para remover o atributo namespace - ele só voltou