How to ignore unknown namespaces using C # XmlReader?

I am trying to read XML string snippets from input using XmlReader , manipulate XDocument and output the result as a string.
If there is a link to an unknown XML namespace, I just want that link to be saved, and not changed in any way.
Note. I don't know the list of possible namespaces, so creating a white list of names in the namespace is not an option.
I am targeting the UWP platform , so XmlTextReader cannot be used here.

Example XML input document:

<VisualState x:Name="Disabled">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

An example of the expected XML output:

<VisualState x:Name="Disabled">
  <VisualState.Setters>
    <Setter Target="RootGrid.Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
    <Setter Target="ContentPresenter.Foreground" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
    <Setter Target="ContentPresenter.BorderBrush" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
  </VisualState.Setters>    
</VisualState>

My current code for parsing XML is:

using (StringReader sr = new StringReader(xml))
{
    using (XmlReader xtr = XmlReader.Create(sr))
    {
        return XDocument.Load(xtr);
    }
}
+4
1

, .

xml.Load(fil);
var ns = new XmlNamespaceManager(xml.NameTable);
var nsNode = xml.DocumentElement.Attributes.GetNamedItem("xmlns");
var nsurl = (nsNode != null) ? nsNode.Value : "";

ns.AddNamespace("ns", nsurl);

XPaths ( ) "ns:" , :

var nodeList = xml.SelectNodes("//ns:whatever", ns);

: XmlDocument, XDocument, .

-1

Source: https://habr.com/ru/post/1673706/


All Articles