views:

563

answers:

1

Hi guys,

I am using Linq To XML to create XML that is sent to a third party. I am having difficulty understanding how to create the XML using Linq when part of information I want to send in the XML will be dynamic.

The dynamic part of the XML is held as a string[,] array. This multi dimensional array holds 2 values.

I can 'build' the dynamic XML up using a stringbuilder and store the values that were in the array into a string variable but when I try to include this variable into Linq the variable is HTMLEncoded rather than included as proper XML.

How would I go about adding in my dynamically built string to the XML being built up by Linq?

For Example:

//string below contains values passed into my class

string[,] AccessoriesSelected;

//I loop through the above array and build up my 'Tag' and store in string called AccessoriesXML


//simple linq to xml example with my AccessoriesXML value passed into it
XDocument RequestDoc = new XDocument(
 new XElement("MainTag",
 new XAttribute("Innervalue", "2")
 ),
AccessoriesXML);

'Tag' is an optional extra, it might appear in my XML multiple times or it might not - it's dependant on a user checking some checkboxes.

Right now when I run my code I see this:

<MainTag> blah blah </MainTag>
&lt ;Tag&gt ;&lt ;InnerTag&gt ; option1="valuefromarray0" option2="valuefromarray1" /&gt ;&lt ;Tag/&gt ;

I want to return something this:

<MainTag> blah blah </MainTag>
<Tag><InnerTag option1="valuefromarray0" option2="valuefromarray1" /></Tag>
<Tag><InnerTag option1="valuefromarray0" option2="valuefromarray1" /></Tag>

Any thoughts or suggestions? I can get this working using XmlDocument but I would like to get this working with Linq if it is possible.

Thanks for your help, Rich

+3  A: 

Building XElements with the ("name", "value") constructor will use the value text as literal text - and escape it if necessary to achieve that.

If you want to create the XElement programatically from a snippet of XML text that you want to actually be interpreted as XML, you should use XElement.Load(). This will parse the string as actual XML, instead of trying to assign the text of the string as an escaped literal value.

Try this:

XDocument RequestDoc = new XDocument(
 new XElement("MainTag",
 new XAttribute("Innervalue", "2")
 ),
 XElement.Load(new StringReader(AccessoriesXML)));
womp
That was it! I won't embarrass myself by saying how long I have been messing around with this to get it working haha! thanks :)
Richard Reddy