I need some xmlns elements in an element with XmWriter

I am trying to convert an XML document from one format to another, and in doing so, I found that I need to insert several xmlns declarations into the root element.

Example:

<? xml version = "1.0" encoding = "utf-8"? > <Template xmlns = "http://tempuri.org/TemplateBase.xsd" XMLNS: TYPES = "http://tempuri.org/TemplateTypes.xsd">
some content
<& pattern GT;

The reason for all this is that I split the XSD schema into several XSDs to reuse generic types in this case.

Well, now I want to write this xml with XmlTextWriter, but I can not write the xmlns attribute for TYPES.

I have tried so far:

XmlWriter xmlWriter = XmlWriter.Create(filename, settings); xmlWriter.WriteStartElement("Template", "http://tempuri.org/TemplateBase.xsd"); xmlWriter.WriteAttributeString("xmlns", "TYPES", "http://tempuri.org/TemplateTypes.xsd", XmlSchema.InstanceNamespace); 

When I run this code, I get the following exception:
System.ArgumentException: the prefix "xmlns" is reserved for using XML ..

Does anyone have a cure for my current headache?

+4
source share
2 answers

Use

 xmlWriter.WriteAttributeString("xmlns", "TYPES", null, "http://tempuri.org/TemplateTypes.xsd"); 

instead

  xmlWriter.WriteAttributeString("xmlns", "TYPES", "http://tempuri.org/TemplateTypes.xsd", XmlSchema.InstanceNamespace); 

This will give you the desired result.

+7
source

It is very simple. Do not write xmlns attributes.

Instead, you should write your attributes and elements in the namespace in which they are located. XmlWriter itself takes care of the namespace declaration (xmlns attributes).

0
source

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


All Articles