XML反序列化-缺少命名空间 [英] XML Deserialization - Missing Namespace

查看:101
本文介绍了XML反序列化-缺少命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在做一个使用XML序列化打开现有XML文件的项目.事实证明,我的项目加载的XML缺少名称空间声明.
创建XML的程序使用此"xlink"名称空间,但从未定义它.由于在我的代码尝试反序列化XML时缺少此名称空间声明,因此引发了异常.在尝试反序列化XML文档之前,是否可以定义此"xlink"命名空间,以使其不会引发异常?

我的代码:

Hi There,
I doing a project that uses XML Serialization to open existing XML files. It turns out that the XML''s that my project loads are missing a namespace declaration.
The program that creates the XML''s uses this "xlink" namespace but it never defines it. Because of this missing namespace declaration when my code tries to deserialize the XML it throws an exception. Is it possible to define this "xlink" namespace before I try to deserialize the XML document so that it won''t throw an exception?

My Code:

XmlSerializer pageDeserializer = new XmlSerializer(typeof(ContentPage));
TextReader pageReader = new StreamReader(pathToFolder + "\\" + Resources.DEFAULT_PAGE_name);
this.contentPage = (ContentPage)pageDeserializer.Deserialize(pageReader);




需要反序列化的示例XML Doucment:




Example XML Doucment that needs to be deserialized:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><svg width="768" height="768"><image x="0" y="0" width="768" height="768" xlink:href="images/mask.png"/></svg>

推荐答案



您可以使用XmlReader并在XmlParserContext/XmlNamespaceManager中设置使用的名称空间来实现此功能.

这是我用来测试的示例代码:
Hi,

You could get this working using a XmlReader and setting the used namespaces in a XmlParserContext / XmlNamespaceManager.

Here is the example code I used to test:
string xml = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
		<svg width=""768"" height=""768"">
		<image x=""0"" y=""0"" width=""768"" height=""768"" xlink:href=""images/mask.png""/>
				</svg>";

XmlSerializer pageDeserializer = new XmlSerializer(typeof(svg));
			
using (TextReader txReader = new StringReader(xml))
{
	// Create XmlReaderSettings
	XmlReaderSettings settings = new XmlReaderSettings();
	settings.ConformanceLevel = ConformanceLevel.Fragment;
	settings.IgnoreWhitespace = true;
	settings.IgnoreComments = true;

	// Create a new NameTable
	NameTable nt = new NameTable();

	// Create a new NamespaceManager
	XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

	// Add your namespaces used in the XML
	nsmgr.AddNamespace("xlink", "urn:http://namespaceurl.com");

	// Create the XmlParserContext using the previous declared XmlNamespaceManager
	XmlParserContext ctx = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

	// Instantiate a new XmlReader, using the previous declared XmlReaderSettings and XmlParserContext
	XmlReader reader = XmlReader.Create(txReader, settings, ctx);

	// Finally, deserialize
	svg deserialize = (svg) pageDeserializer.Deserialize(reader);
}



希望这会有所帮助.

致以最诚挚的问候,祝您编程愉快. 停止



Hope this helps.

Best regards and happy coding,
Stops


这篇关于XML反序列化-缺少命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆