-1

This is my XML:

<location>
  <hotspot name="name1" X="444" Y="518" />
  <hotspot name="name2" X="542" Y="452" /> 
  <hotspot name="name3" X="356" Y="15" />
</location>

what I want to do is:

<location>
  <hotspot name="name1" X="444" Y="518">
    <text>
      This is the text I want to add in
    </text>
  </hotspot>
  <hotspot name="name2" X="542" Y="452" /> 
  <hotspot name="name3" X="356" Y="15" />
</location>

I'm not able to add the text, no problem with the new node.

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
Frank Lioty
  • 949
  • 3
  • 10
  • 17

1 Answers1

3

Since you tagged the question with XmlNode, I'm assuming you're using the XmlDocument type from System.Xml (as opposed to the more modern Linq to XML type XDocument).

To add a new node with some body text, you can create a new element (with the required name) and then set its InnerText value property to specify the text in the node:

// Load XML document and find the parent node
let doc = XmlDocument()
doc.LoadXml("... your xml goes here ...")
let parent = doc.SelectSingleNode("/location/hotspot[@name='name1']")

// Create a new element and set its inner text
let newNode = doc.CreateElement("text")
newNode.InnerText <- "foo"
parent.AppendChild(newNode)

You can also write the same thing by specifying the property when calling CreateElement like this:

doc.CreateElement("text", InnerText = "foo") |> nd.AppendChild
ildjarn
  • 62,044
  • 9
  • 127
  • 211
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • that's right, but does exist a way to have the "text" element not only on a single line but as I wrote in my first post? – Frank Lioty Jun 10 '12 at 22:29
  • @FrankLioty Yes. If you want to add whitespace (such as new line and some spacing), then you can use `parent.AppendChild(doc.CreateWhitespace("\n "))`. – Tomas Petricek Jun 10 '12 at 22:36
  • @FrankLioty Check out this property http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx. Maybe that's reformatting your document. If you add whitespace using `CreateWhitespace` and then get `doc.OuterXml` then you should definitely see _some_ (that's what happens on my machine, at least!) – Tomas Petricek Jun 11 '12 at 02:02