Modifying namespace in XML document programmatically
Modifying namespace in XML document programmatically
static XElement stripNS(XElement root) {
return new XElement(
root.Name.LocalName,
root.HasElements ?
root.Elements().Select(el => stripNS(el)) :
(object)root.Value
);
}
static void Main() {
var xml = XElement.Parse(@"<?xml version=""1.0"" encoding=""utf-16""?>
<ArrayOfInserts xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<insert>
<offer xmlns=""http://schema.peters.com/doc_353/1/Types"">0174587</offer>
<type2 xmlns=""http://schema.peters.com/doc_353/1/Types"">014717</type2>
<supplier xmlns=""http://schema.peters.com/doc_353/1/Types"">019172</supplier>
<id_frame xmlns=""http://schema.peters.com/doc_353/1/Types"" />
<type3 xmlns=""http://schema.peters.com/doc_353/1/Types"">
<type2 />
<main>false</main>
</type3>
<status xmlns=""http://schema.peters.com/doc_353/1/Types"">Some state</status>
</insert>
</ArrayOfInserts>");
Console.WriteLine(stripNS(xml));
}
I needed to validate an XML document with a given XSD document. Seems easy enough… so let’s have a look at the schema first:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://my.namespace"
elementFormDefault="qualified"
targetNamespace="http://my.namespace">
<xs:element name="customer">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string" />
<xs:element name="lastname" type="xs:string" />
<xs:element name="age" type="xs:integer" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The XML instance is:
<?xml version="1.0" encoding="utf-8" ?>
<customer>
<firstname>Homer</firstname>
<lastname></lastname>
<age>36</age>
</customer>
The code is straightforward:
static void Main(string[] args)
{
// Load the xml document
XDocument source = XDocument.Load(@"instance.xml");
// Load the schema
XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
xmlSchemaSet.Add(null, XmlReader.Create(@"customer.xsd"));
// Validate
try { source.Validate(xmlSchemaSet, ValidationCallback, true); }
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
static void ValidationCallback(object sender,
System.Xml.Schema.ValidationEventArgs e)
{
Console.WriteLine(string.Format("[{0}] {1}", e.Severity, e.Message));
}
If you run this, no errors are thrown so it seems to validate. To be sure, let’s change the age in an invalid value:
<Age>invalid!</Age>
and test again. Well… actually, no validation error is thrown in this case either… what’s going on here?
Actually, the XML is not validated at all, because it’s not in the same namespace (http://my.namespace) as the schema definition. This is very dangerous, as we might easily get mislead by thinking that it validates because no errors are thrown. So how do we solve it?
We could ask the sender to provide the correct namespace in the XML file – this would be the best solution because then it would just work – if you try to validate the following XML:
<?xml version="1.0" encoding="utf-8" ?>
<customer xmlns="http://my.namespace">
<firstname>Homer</firstname>
<lastname></lastname>
<age>invalid</age>
</customer>
…then the validation error is thrown, because the namespaces now match:

Unfortunately, it is not always possible to change the XML file, so how can we bypass this namespace conflict? If appears that if we would change the namespace in the loaded XML document to the one we are using in our schema, the conflict is resolved. A first attempt may be:
// Load the xml document
XDocument source = XDocument.Load(@"instance.xml");
// Change namespace to reflect schema namespace
source.Root.SetAttributeValue("xmlns", "http://my.namespace");
// Load the schema
XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
xmlSchemaSet.Add(null, XmlReader.Create(@"customer.xsd"));
// Validate
try { source.Validate(xmlSchemaSet, ValidationCallback, true); }
catch (Exception ex) { Console.WriteLine(ex.Message); }
If we run this, the validation error is still not thrown, so setting the namespace attribute is not enough. The reason is that once the XDocument is loaded, every element in the tree gets prefixed with the namespace name. So we need to change them all, and so I wrote the following method that does this:
static void Main(string[] args)
{
// Load the xml document
XDocument source = XDocument.Load(@"instance.xml");
// Change namespace to reflect schema namespace
source = SetNamespace(source,"http://my.namespace");
// Load the schema
XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
xmlSchemaSet.Add(null, XmlReader.Create(@"customer.xsd"));
// Validate
try { source.Validate(xmlSchemaSet, ValidationCallback, true); }
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
public static XDocument SetNamespace(XDocument source, XNamespace xNamespace)
{
foreach (XElement xElement in source.Descendants())
{
// First make sure that the xmlns-attribute is changed
xElement.SetAttributeValue("xmlns", xNamespace.NamespaceName);
// Then also prefix the name of the element with the namespace
xElement.Name = xNamespace + xElement.Name.LocalName;
}
return source;
}
static void ValidationCallback(object sender,
System.Xml.Schema.ValidationEventArgs e)
{
Console.WriteLine(string.Format("[{0}] {1}", e.Severity, e.Message));
}
The SetNameSpace method will set the corrrect namespace for each element in the XDocument. And if we run it now, the validation error is thrown again because the namespace in the XDocument has been modified and matches the schema namespace.
Related
Parsing large XML filesIn "C#"
Strategy patternIn "C#"
A reference architecture (part 7)In "Architecture"
3 thoughts on “Modifying namespace in XML document programmatically”
- Janez says:
Thanks, a working solution to a problem that took the better part of my day. :-)
- Jim says:
This solution was very hard to fine…thanks so much for posting it.
- Mike says:
This was very helpful and got me past some serious frustration! I was changing a child element tree to match a parent namespace, but I did not want to have the extra size of including the SetAttributeValue on all elements. My change was a change from one default namespace to another existing and prefixed one. This did the trick for me. Below are some minor adjustments that might be useful to others in some cases.
public static XDocument SetNamespace(XDocument source, XNamespace original, XNamespace target)
{
//First change the element name (and namespace)
foreach (XElement xElement in source.Descendants().Where(x => x.Name.Namespace == original))
xElement.Name = target + xElement.Name.LocalName;//Second, remove the default namespace attribute.
foreach (XElement xElement in source.Descendants().Where(x => x.Attributes().Where(y => y.Name == “xmlns”).Count() > 0))
xElement.Attribute(“xmlns”).Remove();return source;
}
Leave a Reply
Modifying namespace in XML document programmatically的更多相关文章
- parsing XML document from class path resource
遇到问题:parsing XML document from class path resource [spring/resources] 解决方法:项目properties— source—remo ...
- eclipse错误:Unable to read workbench state. Workbench UI layout will be reset.XML document structures
Unable to read workbench state. Workbench UI layout will be reset.XML document structures must start ...
- parsing XML document from class path resource [config/applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [config/applicationContext.xml] 解决方案
parsing XML document from class path resource [config/applicationContext.xml]; nested exception is j ...
- 解决SoapFault (looks like we got no XML document)问题
今天在调试项目的时候出现下面的错误信息: SoapFault looks like we got no XML document (D:\phpStudy\WWW\self.shop.xunmall. ...
- 出错: IOException parsing XML document from ServletContext resource [/cn.mgy.conig]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/cn.mgy.conig]
错误的详细内容: 严重: StandardWrapper.Throwable org.springframework.beans.factory.BeanDefinitionStoreExceptio ...
- (转)EVMON_FORMAT_UE_TO_TABLES procedure - move an XML document to relational tables
原文:https://www.ibm.com/support/knowledgecenter/zh/SSEPGG_9.8.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0054 ...
- org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: c
//这个是 配置文件放错了地方 org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing ...
- IOException parsing XML document from class path resource [WebRoot/WEB-INF/applicationContext.xml];
parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io. ...
- Office 365 - For security reasons DTD is prohibited in this XML document
博客地址:http://blog.csdn.net/FoxDave 今天在测试东西的时候发现在本机运行CSOM代码或使用Office 365 PowerShell时,出现了如下错误: Connec ...
随机推荐
- ORM常用操作
一般操作 专业官网文档 必会13条查询 <> all(): 查询所有结果 <> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象 <> get ...
- Python之RabbitMQ的使用
今天总结一下Python关于Rabbitmq的使用 RabbitMQ官网说明,其实也是一种队列,那和前面说的线程queue和进程queue有什么区别呢? 线程queue只能在同一个进程下进行数据交互 ...
- c++ stl源码剖析学习笔记(二)iterator
ITERATOR 迭代器 template<class InputIterator,class T> InputIterator find(InputIterator first,Inpu ...
- [IBM][CLI Driver] SQL0270N 函数不受支持(原因码:"75")。 SQLSTATE=42997
db2 update dbm cfg using FEDERATED yes 与 自动维护 (AUTO_MAINT) = ON 自动数据库备份 (AUTO_DB_BACKUP) = OFF 自动表 ...
- scp复制文件到指定端口
1.scp基本格式 scp file user@host:/dir 2.scp复制文件到指定端口 scp默认连接的端口是22端口,如果ssh不是使用标准的22端口则使用-P(P大写)指定: scp - ...
- 125 open source Big Data architecture papers for data professionals
https://www.linkedin.com/pulse/100-open-source-big-data-architecture-papers-anil-madan
- 配置docker官方源并用yum安装docker
一.docker的官方安装文档: https://docs.docker.com/engine/installation/linux/centos/ 由docker给的文档可以看出它也只是去配置了一个 ...
- [转]语音识别中区分性训练(Discriminative Training)和最大似然估计(ML)的区别
转:http://blog.sina.com.cn/s/blog_66f725ba0101bw8i.html 关于语音识别的声学模型训练方法已经是比较成熟的方法,一般企业或者研究机构会采用HTK工具包 ...
- 五花八门的CSS
一.颜色 rgba(0, 0, 0, 0.5) rgba括号中前3个数字代表着 red green blue三种颜色的rgb值,0-255,最后一个是设定这个颜色的透明度即alpha值.范围从0到1, ...
- 09-部署配置kubedns插件
安装和配置 kubedns 插件 官方的yaml文件在:kubernetes/cluster/addons/dns. 该插件直接使用kubernetes部署,官方的配置文件中包含以下镜像: gcr.i ...