简体   繁体   English

查找未声明的命名空间'前缀

[英]Find undeclared namespace'prefix

I'd like to retrieve each undeclared namespaces' prefix in a Xml file on load using (where msCurrentContent is a memorystream) : 我想在加载时使用(其中msCurrentContent是一个msCurrentContent )在Xml文件中检索每个未声明的名称空间的前缀:

xmlCurrentDoc = new XmlDocument();
xmlCurrentDoc.Load(msCurrentContent);

For example, when loading a Xml file with the following declaration : <Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="mondoc" xls:schemaLocation="mondoc.xsd"> 例如,使用以下声明加载Xml文件时: <Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="mondoc" xls:schemaLocation="mondoc.xsd">

It must retrieve the undeclared prefix xls without throwing an exception (as it does know). 它必须检索未声明的前缀xls而不抛出异常(因为它知道)。

What is the best way to do this ? 做这个的最好方式是什么 ?

Thanks for your help ! 谢谢你的帮助 !

This is really hacky, but you could subclass XmlNamespaceManager and add fake namespaces as you encounter unknown prefixes: 这真的很麻烦,但你可以XmlNamespaceManager并在遇到未知前缀时添加假名称空间:

public class MyXmlNamespaceManager : XmlNamespaceManager
{
    const string DefaultMissingNamespacePrefix = "http://missing.namespace.prefix.net/2014/";

    private string MissingNamespacePrefix { get; set; }
    private int NextMissingNamespaceIndex { get; set; }

    // The dictionary consists of a collection of namespace names keyed by prefix.
    public Dictionary<string, List<string>> MissingNamespaces { get; private set; }

    public MyXmlNamespaceManager(XmlNameTable nameTable)
        : this(nameTable, null) { }

    public MyXmlNamespaceManager(XmlNameTable nameTable, string missingNamespacePrefix)
        : base(nameTable)
    {
        this.MissingNamespacePrefix = (string.IsNullOrEmpty(missingNamespacePrefix) ? DefaultMissingNamespacePrefix : missingNamespacePrefix);
        this.MissingNamespaces = new Dictionary<string, List<string>>();
    }

    void AddMissingNamespace(string prefix)
    {
        if (string.IsNullOrEmpty(prefix))
            return;

        string uri;
        do
        {
            int index = NextMissingNamespaceIndex++;
            uri = MissingNamespacePrefix + index.ToString();
        }
        while (LookupPrefix(uri) != null); // Just in case.

        Debug.WriteLine(string.Format("Missing namespace \"{0}\" found, added fake namespace \"{1}\"", prefix, uri));
        AddNamespace(prefix, uri);
        MissingNamespaces.Add(prefix, uri);
    }

    public override bool HasNamespace(string prefix)
    {
        var result = base.HasNamespace(prefix);
        if (!result)
            AddMissingNamespace(prefix);
        result = base.HasNamespace(prefix);
        return result;
    }

    public override string LookupNamespace(string prefix)
    {
        var result = base.LookupNamespace(prefix);
        if (result == null)
            AddMissingNamespace(prefix);
        result = base.LookupNamespace(prefix);
        return result;
    }
}

public static class DictionaryExtensions
{
    public static void Add<TKey, TValue>(this IDictionary<TKey, List<TValue>> listDictionary, TKey key, TValue value)
    {
        if (listDictionary == null)
            throw new ArgumentNullException();
        List<TValue> values;
        if (!listDictionary.TryGetValue(key, out values))
        {
            listDictionary[key] = values = new List<TValue>();
        }
        values.Add(value);
    }
}

And then, to test: 然后,测试:

        string xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?>
<Document xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""mondoc"" xls:schemaLocation=""mondoc.xsd"">
</Document>
";
        XmlDocument xmlDoc;

        using (var stream = new StringReader(xml))
        {
            var settings = new XmlReaderSettings();
            settings.NameTable = new NameTable();
            var manager = new MyXmlNamespaceManager(settings.NameTable);
            XmlParserContext context = new XmlParserContext(null, manager, null, XmlSpace.Default);
            using (var xmlReader = XmlReader.Create(stream, settings, context))
            {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlReader);
            }
        }

        string newXml;
        using (var writer = new StringWriter())
        {
            xmlDoc.Save(writer);
            newXml = writer.ToString();
        }

        Debug.WriteLine(newXml);

Which produces the following result: 这产生以下结果:

<?xml version="1.0" encoding="utf-16" standalone="no"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="mondoc" xls:schemaLocation="mondoc.xsd" xmlns:xls="http://missing.namespace.prefix.net/2014/0">
</Document>

At least, it's not an exception. 至少,这不是一个例外。 Note - only partially tested. 注意 - 仅部分测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM