Insert raw XML string in XElement

I am trying to load node (in string format) in XElement. Although this should be easy enough, I find some problems:

  • node I'm trying to load contains namespace links in some sub-nodes
  • When I try to use XElement.Load() or Xelement.Parse() , I get the expected undefined namespace error

I know that the solution is to create a node environment with namespace definitions and then load it all, but I was wondering if there is a more elegant solution that does not include string operations.

Here is my unsuccessful attempt: (

I have a set of namespace attributes:

 private readonly List<XAttribute> _namespaces; 

It is already populated and contains all the necessary namespaces. So, to embed my XML string into another node, I did this:

 var temp = new XElement("root", (from ns in _namespaces select ns), MyXMLString); 

But, as I expected, the content of MyXMLString gets the escape code and becomes the text node. As a result, I get the following:

 <root xmlns:mynamespace="http://mynamespace.com">&lt;mynamespace:node&gt;node text&lt;/node&gt;</root> 

And the result I'm looking for is:

 <root xmlns:mynamespace="http://mynamespace.com"> <mynamespace:node>node text</node> </root> 

Is there a neat way to do this?

Thanks in advance

+4
source share
1 answer

Presumably, your XML text is actually well-formed (note the namespace qualifier for the closing tag):

 var xml = "<mynamespace:node>node text</mynamespace:node>"; 

In this case, you can use this to manually specify namespaces:

 var mngr = new XmlNamespaceManager( new NameTable() ); mngr.AddNamespace( "mynamespace", "urn:ignore" ); // or proper URL var parserContext = new XmlParserContext(null, mngr, null, XmlSpace.None, null); 

Now read and download:

 var txtReader = new XmlTextReader( xml, XmlNodeType.Element, parserContext ); var ele = XElement.Load( txtReader ); 

It works as expected. And you don’t need the β€œroot” node shell. Now it can be inserted into any, like XElement anywhere.

+5
source

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


All Articles