473,461 Members | 1,697 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

[XML] Graceful creation and appending

EARNEST
128 100+
Hello guys,

here is what I did so far. I prefer the way you create in the first condition. however, i do not know how to append new elements in the similar way.
is there a way to reduce amount of code in 2nd condition?

Desired output:

Code:
<?xml version="1.0" encoding="utf-8" ?>
- <Definitions>
- <Definition>
<Acronym>a1</Acronym>
<Name>n1</Name>
- <Value>
<A>1</A>
<B>2</B>
<Alpha>3</Alpha>
<Beta>4</Beta>
</Value>
</Definition>
- <Definition>
<Acronym>test2</Acronym>
<Name>test22</Name>
- <Value>
<A>551</A>
<B>23</B>
<Alpha>0.12</Alpha>
<Beta>-95.21</Beta>
</Value>
</Definition>
</Definitions>
Expand|Select|Wrap|Line Numbers
  1.  public void CreateXML_Definition(Definition definition)
  2.         {
  3.             string filename;
  4.             Stream xmlFile;
  5.             XmlDocument xmlDoc;
  6.  
  7.             filename = "definitions.xml";
  8.  
  9.             if (!File.Exists(filename))
  10.             {
  11.                 xmlFile = new FileStream(filename, FileMode.Create);
  12.  
  13.                 using (XmlTextWriter xmlWriter = new XmlTextWriter(xmlFile, Encoding.UTF8))
  14.                 {
  15.                     xmlWriter.WriteStartDocument();
  16.                         xmlWriter.WriteStartElement("Definitions");
  17.  
  18.                             xmlWriter.WriteStartElement("Definition");
  19.                             xmlWriter.WriteElementString("Acronym", definition.DefinitionAcronym);
  20.                             xmlWriter.WriteElementString("Name", definition.DefinitionName);
  21.  
  22.                             xmlWriter.WriteStartElement("Value");
  23.                                 xmlWriter.WriteElementString("A", definition.DefinitionValue.A.ToString());
  24.                                 xmlWriter.WriteElementString("B", definition.DefinitionValue.B.ToString());
  25.                                 xmlWriter.WriteElementString("Alpha", definition.DefinitionValue.Alpha.ToString());
  26.                                 xmlWriter.WriteElementString("Beta", definition.DefinitionValue.Beta.ToString());
  27.                             xmlWriter.WriteEndElement();
  28.  
  29.                         xmlWriter.WriteEndElement();
  30.                     xmlWriter.WriteEndDocument();
  31.                 }
  32.             }
  33.             else
  34.             {
  35.                 xmlDoc = new XmlDocument();
  36.  
  37.                 xmlDoc.Load(filename);
  38.  
  39.                 XmlElement subRoot = xmlDoc.CreateElement("Definition");
  40.  
  41.                 XmlElement acronym = xmlDoc.CreateElement("Acronym");
  42.                 XmlText xmlAcronym = xmlDoc.CreateTextNode(definition.DefinitionAcronym);
  43.                 acronym.AppendChild(xmlAcronym);
  44.                 subRoot.AppendChild(acronym);
  45.                 xmlDoc.DocumentElement.AppendChild(subRoot);
  46.  
  47.                 XmlElement name = xmlDoc.CreateElement("Name");
  48.                 XmlText xmlName = xmlDoc.CreateTextNode(definition.DefinitionName);
  49.                 name.AppendChild(xmlName);
  50.                 subRoot.AppendChild(name);
  51.                 xmlDoc.DocumentElement.AppendChild(subRoot);
  52.  
  53.                 XmlElement value = xmlDoc.CreateElement("Value");
  54.                 subRoot.AppendChild(value);
  55.                 xmlDoc.DocumentElement.AppendChild(subRoot);
  56.  
  57.                     XmlElement xmlValue_A = xmlDoc.CreateElement("A");
  58.                     XmlText val_A = xmlDoc.CreateTextNode(definition.DefinitionValue.A.ToString());
  59.                     xmlValue_A.AppendChild(val_A);
  60.                     value.AppendChild(xmlValue_A);
  61.                     xmlDoc.DocumentElement.AppendChild(subRoot);
  62.  
  63.                     XmlElement xmlValue_B = xmlDoc.CreateElement("B");
  64.                     XmlText val_B = xmlDoc.CreateTextNode(definition.DefinitionValue.B.ToString());
  65.                     xmlValue_B.AppendChild(val_B);
  66.                     value.AppendChild(xmlValue_B);
  67.                     xmlDoc.DocumentElement.AppendChild(subRoot);
  68.  
  69.                     XmlElement xmlValue_C = xmlDoc.CreateElement("Alpha");
  70.                     XmlText val_C = xmlDoc.CreateTextNode(definition.DefinitionValue.Alpha.ToString());
  71.                     xmlValue_C.AppendChild(val_C);
  72.                     value.AppendChild(xmlValue_C);
  73.                     xmlDoc.DocumentElement.AppendChild(subRoot);
  74.  
  75.                     XmlElement xmlValue_D = xmlDoc.CreateElement("Beta");
  76.                     XmlText val_D = xmlDoc.CreateTextNode(definition.DefinitionValue.Beta.ToString());
  77.                     xmlValue_D.AppendChild(val_D);
  78.                     value.AppendChild(xmlValue_D);
  79.                     xmlDoc.DocumentElement.AppendChild(subRoot);
  80.  
  81.                 xmlDoc.Save(filename);
  82.             }  
  83.         }
Dec 14 '10 #1

✓ answered by GaryTexmo

Why not create a method that packages up all that duplicate code you've got there? Supply the appropriate parameters and return an XmlNode?

You can do this in more places as well... anywhere you find yourself duplicating a good bit of code, it's probably a good idea to create a new method.

12 2212
GaryTexmo
1,501 Expert 1GB
Why not create a method that packages up all that duplicate code you've got there? Supply the appropriate parameters and return an XmlNode?

You can do this in more places as well... anywhere you find yourself duplicating a good bit of code, it's probably a good idea to create a new method.
Dec 14 '10 #2
EARNEST
128 100+
@GaryTexmo,
thanks mate. good idea...totally forgot about it.
quick "prototype", haven't taken into account everything for now. what do you think?

Expand|Select|Wrap|Line Numbers
  1. public void CreateXML_Definition(Definition definition)
  2.         {
  3.             string filename;     
  4.             Stream xmlFileStream;
  5.             XmlDocument xmlDoc;
  6.  
  7.             string def_Root = "Definitions";
  8.             string def_Catg = "Definition";
  9.             string def_Acro = "Acronym";
  10.             string def_Name = "Name";
  11.             string def_Val = "Value";
  12.             string def_Val_A = "A";
  13.             string def_Val_B = "B";
  14.             string def_Val_Alpha = "Alpha";
  15.             string def_Val_Beta = "Beta";
  16.  
  17.             filename = "definitions.xml";
  18.  
  19.             if (!File.Exists(filename))
  20.             {
  21.                 xmlFileStream = new FileStream(filename, FileMode.Create);
  22.  
  23.                 using (XmlTextWriter xmlTextWriter = new XmlTextWriter(xmlFileStream, Encoding.UTF8))
  24.                 {
  25.                     xmlTextWriter.WriteStartDocument();
  26.                         xmlTextWriter.WriteStartElement("Definitions");
  27.  
  28.                         //take into account Root issue, need to create it
  29.  
  30.  
  31.                         xmlTextWriter.WriteEndElement();
  32.                     xmlTextWriter.WriteEndDocument();
  33.                 }
  34.             }
  35.             else
  36.             {
  37.                 xmlDoc = new XmlDocument();
  38.                 xmlDoc.Load(filename);
  39.  
  40.                 List<XmlNode> list_OfNodes = new List<XmlNode>();
  41.  
  42.                 XmlNode tag_Definitions = xmlDoc.SelectSingleNode(def_Root);
  43.  
  44.                 XmlNode tag_Definition = getNode(def_Catg, null, xmlDoc);
  45.  
  46.                 XmlNode tag_Acronym = getNode(def_Acro, definition.DefinitionAcronym.ToString(), xmlDoc);
  47.                 XmlNode tag_Name = getNode(def_Name, definition.DefinitionName.ToString(), xmlDoc);
  48.  
  49.                 XmlNode tag_Value = getNode(def_Val, null, xmlDoc);
  50.  
  51.                     XmlNode tag_A = getNode(def_Val_A, definition.DefinitionValue.A.ToString(), xmlDoc);
  52.                     XmlNode tag_B = getNode(def_Val_B, definition.DefinitionValue.B.ToString(), xmlDoc);
  53.                     XmlNode tag_Alpha = getNode(def_Val_Alpha, definition.DefinitionValue.Alpha.ToString(), xmlDoc);
  54.                     XmlNode tag_Beta = getNode(def_Val_Beta, definition.DefinitionValue.Beta.ToString(), xmlDoc);
  55.  
  56.  
  57.                     tag_Value.AppendChild(tag_A);
  58.                     tag_Value.AppendChild(tag_B);
  59.                     tag_Value.AppendChild(tag_Alpha);
  60.                     tag_Value.AppendChild(tag_Beta);
  61.  
  62.                     tag_Definition.AppendChild(tag_Acronym);
  63.                     tag_Definition.AppendChild(tag_Name);
  64.                     tag_Definition.AppendChild(tag_Value);
  65.  
  66.                     tag_Definitions.AppendChild(tag_Definition);
  67.  
  68.                xmlDoc.Save(filename);
  69.  
  70.             }  
  71.         }
  72.  
  73.         public XmlNode getNode(string tagName, string attValue, XmlDocument xmlDoc)
  74.         {
  75.             XmlNode node;
  76.  
  77.             node = xmlDoc.CreateNode(XmlNodeType.Element, tagName, null);
  78.             node.InnerText = attValue;
  79.  
  80.             return node;
  81.         }
  82.  
  83.         public XmlNode getNode(XmlNode node_Parent, string tagName, string attValue, XmlDocument xmlDoc)
  84.         {
  85.             XmlNode node;
  86.  
  87.             node = xmlDoc.CreateNode(XmlNodeType.Element, tagName, null);
  88.             node.InnerText = attValue;
  89.  
  90.             node_Parent.AppendChild(node);
  91.  
  92.             return node;
  93.         }        
Dec 15 '10 #3
GaryTexmo
1,501 Expert 1GB
I think that's fine :) One other thing to suggest... instead of these lines:

Expand|Select|Wrap|Line Numbers
  1.      string def_Root = "Definitions";
  2.             string def_Catg = "Definition";
  3.             string def_Acro = "Acronym";
  4.             string def_Name = "Name";
  5.             string def_Val = "Value";
  6.             string def_Val_A = "A";
  7.             string def_Val_B = "B";
  8.             string def_Val_Alpha = "Alpha";
  9.             string def_Val_Beta = "Beta";
Perhaps consider putting them as constants within your class. That way they're right up at the top and you can change things if you ever need to.

Not a big deal, but I've found it to help when I work with XML.
Dec 15 '10 #4
EARNEST
128 100+
Thanks, also I tried to use more of a "smarter" way. but facing a problem when I add element by element.
Here is what i get

Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3.   <Acronym>a</Acronym>
  4.   <Name>b</Name>
  5.   <Value>
  6.     <A>1</A>
  7.     <B>2</B>
  8.     <Alpha>3</Alpha>
  9.     <Beta>4</Beta>
  10.   </Value>
  11. </Definitions><?xml version="1.0" encoding="utf-8"?>
  12. <Definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  13.   <Acronym>a</Acronym>
  14.   <Name>b</Name>
  15.   <Value>
  16.     <A>1</A>
  17.     <B>2</B>
  18.     <Alpha>34</Alpha>
  19.     <Beta>4</Beta>
  20.   </Value>
  21. </Definitions>
and there is the code
Expand|Select|Wrap|Line Numbers
  1.         public void SerializeToXML(Definition definition)
  2.         {
  3.             if (File.Exists("definitions.xml"))
  4.             {
  5.                 XmlSerializer xmlSerializer = new XmlSerializer(typeof(Definition));
  6.                 FileInfo fileInfo = new FileInfo("definitions.xml");
  7.                 Stream inStream = fileInfo.OpenRead();
  8.                 Definition tempDef = xmlSerializer.Deserialize(inStream) as Definition;
  9.                 inStream.Close();
  10.  
  11.                 tempDef = definition;
  12.  
  13.                 StreamWriter sw = fileInfo.AppendText();
  14.  
  15.                 xmlSerializer.Serialize(sw, tempDef);
  16.                 sw.Close();
  17.  
  18.  
  19.             }
  20.             else
  21.             {
  22.                 XmlSerializer xmlSerializer = new XmlSerializer(typeof(Definition));
  23.                 TextWriter textWriter = new StreamWriter("definitions.xml");
  24.                 xmlSerializer.Serialize(textWriter, definition);
  25.                 textWriter.Close();
  26.             }
  27.         }
Dec 15 '10 #5
GaryTexmo
1,501 Expert 1GB
What's the problem? Is it that you don't have an encompassing root node?
Dec 15 '10 #6
EARNEST
128 100+
Should be of this form

Expand|Select|Wrap|Line Numbers
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3. <Definition>
  4.   <Acronym>a</Acronym>
  5.   <Name>b</Name>
  6.   <Value>
  7.     <A>1</A>
  8.     <B>2</B>
  9.     <Alpha>3</Alpha>
  10.     <Beta>4</Beta>
  11.   </Value>
  12. </Definition>
  13. <Definition>
  14.   <Acronym>a</Acronym>
  15.   <Name>b</Name>
  16.   <Value>
  17.     <A>1</A>
  18.     <B>2</B>
  19.     <Alpha>3</Alpha>
  20.     <Beta>4</Beta>
  21.   </Value>
  22. </Definition>
  23. <Definition>
  24.   <Acronym>a</Acronym>
  25.   <Name>b</Name>
  26.   <Value>
  27.     <A>1</A>
  28.     <B>2</B>
  29.     <Alpha>3</Alpha>
  30.     <Beta>4</Beta>
  31.   </Value>
  32. </Definition>
  33. </Definitions>
  34.  
Dec 15 '10 #7
GaryTexmo
1,501 Expert 1GB
Well, it looks like you're adding your properties to the definitions node, instead of creating a definition node and adding to that, then adding each definition to the definitions node.

Take a look at your processing to see where you are adding nodes and to what :) I'm betting you're adding stuff directly to your XML document... generally you want to do this:

(NOTE: I may have the syntax off since I'm doing this from memory, but you get the idea...)
Expand|Select|Wrap|Line Numbers
  1. XmlDocument xmlDoc = new XmlDocument();
  2. xmlDoc.LoadXml(some xml file)
  3. XmlNode rootNode = xmlDoc.DocumentElement;
  4.  
  5. foreach (item in our set of items)
  6. {
  7.   XmlNode itemNode = CreateItemNode(xmlDoc, item);
  8.   rootNode.AppendChild(itemNode);
  9. }
Are you appending to the root node?
Dec 15 '10 #8
EARNEST
128 100+
that is what i did before that, i'm now trying to use Serialization for it
Dec 15 '10 #9
GaryTexmo
1,501 Expert 1GB
Oh, I see now. I don't know off-hand, but maybe it has something to do with the fact that you're serializing a single definition instead of, say, a list of definitions?

I'm not sure how you're getting that output though because it looks like you're only doing a single write on a definition, yet you're getting a definitions node.

I'm not seeing anything else with what's here, I think you're just going to have to go through your code again. If you're still having trouble, please start a new thread with an appropriate title. You've already chosen an answer for this one so lets deal with the new issue separately :)
Dec 15 '10 #10
EARNEST
128 100+
Even if i will serialize a list of definitions, that's not a point. the problem is that I cannot add to an XML file that is already there. Using the following code, i have bad-formed XML.

Expand|Select|Wrap|Line Numbers
  1.         /// <summary>
  2.         /// not working 
  3.         /// </summary>
  4.         /// <param name="definition"></param>
  5.         public void SerializeToXML(Definition definition)
  6.         {
  7.             if (File.Exists("definitions.xml"))
  8.             {
  9.                 XmlSerializer xmlSerializer = new XmlSerializer(typeof(Definition));
  10.                 FileInfo fileInfo = new FileInfo("definitions.xml");
  11.                 Stream inStream = fileInfo.OpenRead();
  12.                 Definition tempDef = xmlSerializer.Deserialize(inStream) as Definition;
  13.                 inStream.Close();
  14.  
  15.                 tempDef = definition;
  16.  
  17.                 StreamWriter sw = fileInfo.AppendText();
  18.  
  19.                 xmlSerializer.Serialize(sw, tempDef);
  20.                 sw.Close();              
  21.             }
  22.             else
  23.             {
  24.                 XmlSerializer xmlSerializer = new XmlSerializer(typeof(Definition));
  25.                 TextWriter textWriter = new StreamWriter("definitions.xml");
  26.                 xmlSerializer.Serialize(textWriter, definition);
  27.                 textWriter.Close();
  28.             }
  29.         }
Dec 15 '10 #11
GaryTexmo
1,501 Expert 1GB
Please make a new thread for this and repost the appropriate details.

Thanks!
Dec 15 '10 #12
EARNEST
128 100+
Done. thanks
Dec 15 '10 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Che | last post by:
Being a total novice at this sort of thing I thought that I'd ask you good folk before I bark up the wrong tree. I have an XSD file and a text file, and what I would like to try is to create an...
0
by: Doug Day | last post by:
I'm relatively new to XML, so I hope my question is not too obtuse: Are there any available products that will generate valid XML documents based on a given XML schema and a data file to populate...
1
by: sam.collett | last post by:
Is there a basic guide on Xml document creation and editing (simpler than the MSDN docs). Say I want to create a file containing the following: <?xml version="1.0" encoding="utf-8"...
4
by: PZWU | last post by:
How can I build a big XML file by appending a few smaller xml files in C#? Below is what I've been trying: /* FileString.xml is the path and name string of the big xml file*/ XmlTextWriter...
8
by: Sam Collett | last post by:
Is there a basic guide on Xml document creation and editing (simpler than the MSDN docs). Say I want to create a file containing the following: <?xml version="1.0" encoding="utf-8"...
1
by: Lerp | last post by:
Hi all, I have a question regarding the best way to build a dynamic XML document from data stored in my database. From what I have read so far, I could build a dataset and then use this...
4
by: Sai | last post by:
I am new to this area,please bear with me for this basic question. :) I have an xml schema file xyz.xsd file with me,That contains request and response xml schema ,how can I proceed to create a...
1
dizyn
by: dizyn | last post by:
I want to create an xml using php and i want to save hashed password in it, Please tell me simplest way to do so. aboved mentioned error happend with i used this code for xml file creation. ...
0
by: ultradiv | last post by:
I have a VB.NET application partly built that produces an xml output (just a file at present) I have a .NET webserver and SQLserver 2000 I need to be able to send the xml to the webserver/database...
0
by: Udo | last post by:
Hello, is it possible to use MSXML and a Schema with high-level methods (or any other way) for creating valid XML-Nodes interactively. That means I don't want to validate an entire XML-document,...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.