views:

36

answers:

1

Hello everyone,

I am using VSTS 2008 + C# + .Net 3.5 to conversion the below input XML file into destination format. There may be arbitrary number of Image elements. And the new Price information is provided in List.

Any quick way to implement the conversion function?

source format,

<?xml version="1.0"?>
<Metadata version="1">
  <Owner>George</Owner>
  <Image>
    <x>100</x>
  </Image>
  <Image>
    <x>200</x>
  </Image>
</Metadata>

destination format,

<?xml version="1.0"?>
<Metadata version="1">
  <Owner>George</Owner>
  <Image>
    <x>100</x>
    <Price>200</Price>
  </Image>
  <Image>
    <x>100</x>
    <Price>300</Price>
  </Image>
</Metadata>

thanks in advance, George

+3  A: 

Quite simply: select all <Image> nodes and add a new <Price> child node to them:

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("your-filename-here.xml");

XmlNodeList imageList = xmldoc.SelectNodes("/Metadata/Image");

foreach(XmlNode node in imageList)
{
   XmlElement priceElement = xmldoc.CreateElement("Price");
   priceElement.InnerText = "300";  // or whatever it is

   node.AppendChild(priceElement);
}

xmldoc.Save("your-new-xml-file-name-here.xml");

This should do it, I hope!

Marc

marc_s
I was working out the same, that's a straightforward way to do it
Abel
"that's a straightforward way to do it" -- what is it?
George2
@Abel: I like straightforward - I don't like "black voodoo magic" where you don't see what's happening :-)
marc_s
Marc, a further question, if I need to append string type elements, how to handle XML escape issue? I think we need manually escape some special XML character before set InnerText property?
George2
marc_s
@George2: see this other SO question about just that topic: http://stackoverflow.com/questions/949122/insert-text-node-to-xml-document-containing-xml
marc_s
Marc, I have a new idea. I think using CDATA may make the XML file look not very clear and a little messy. I think using XML serializer/deserializer should be better -- because it will handle XML escape for me automatically (i.e. when deserialize, XML serializer will un-escape, when serialize XML serializer escape). Any comments about my points and using XML serializer?
George2
Another issue of using CDATA is, I have no way to know easily whether the content of InnerText contains characters which needs to be escaped or not. So, I have to put all content of InnerText into CDATA block. Is this point correct?
George2
Using the XmlSerializer should work ok, yes. And you could always check your string for those "dangerous" characters and only use a CDATA section if any of those are really present - but that's a bit more work when creating the file, obviously.
marc_s
Thanks Marc, question answered.
George2