|
||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Introduction
Using the codeThe Start off with the private string insert(string sourceXml, string targetXml)
{
...
}
First, the // Declare and set readers and writers for sourceXml
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringReader stringReader =
new System.IO.StringReader(sourceXml);
System.IO.StringWriter stringWriter =
new System.IO.StringWriter(sb);
System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(stringReader);
System.Xml.XmlTextWriter xmlWriter =
new System.Xml.XmlTextWriter(stringWriter);
string strValidSourceXml = String.Empty;
string strValidTargetXml = String.Empty;
string strRootName = String.Empty;
string[,] arrRootAtts = null;
The source XML is read, validated, and written into the try
{
while(xmlReader.Read())
{
xmlWriter.WriteNode(xmlReader,true);
}
}
catch(System.Xml.XmlException e)
{
MessageBox.Show(this,
"Error parsing source XML\n\nMessage: " + e.Message,
"Parser Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
return String.Empty;
}
strValidSourceXml = sb.ToString();
After reading the source, the readers and writers must be reset to parse the target XML. // Reset readers and writers for targetXml
sb = new System.Text.StringBuilder();
stringReader = new System.IO.StringReader(targetXml);
stringWriter = new System.IO.StringWriter(sb);
xmlReader = new System.Xml.XmlTextReader(stringReader);
xmlWriter = new System.Xml.XmlTextWriter(stringWriter);
Then the root element is broken into its components - name and attributes. The inner XML from the root is read into a string variable. try
{
while(xmlReader.Read())
{
// Parse root node and store name and attributes
strRootName = xmlReader.Name;
if(xmlReader.HasAttributes)
{
int i = 0;
arrRootAtts = new string[xmlReader.AttributeCount,2];
while(xmlReader.MoveToNextAttribute())
{
arrRootAtts[i,0] = xmlReader.Name;
arrRootAtts[i,1] = xmlReader.Value;
i++;
}
}
// Store inner XML as string
strValidTargetXml = xmlReader.ReadInnerXml();
}
}
catch(System.Xml.XmlException e)
{
MessageBox.Show(this,
"Error parsing target XML\n\nMessage: " + e.Message,
"Parser Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
return String.Empty;
}
The root node and its attributes are written out to a // Combine root node with source and target XML strings
xmlWriter.WriteStartElement(strRootName);
if (arrRootAtts != null)
{
for (int i = 0; i < arrRootAtts.GetLength(0); i++)
{
xmlWriter.WriteAttributeString(arrRootAtts[i,0],
arrRootAtts[i,1]);
}
}
xmlWriter.WriteRaw(strValidTargetXml + strValidSourceXml);
xmlWriter.WriteEndElement();
Finally, the method returns the string from the return sb.ToString();
Memory SavingsBe aware that the In my testing, for combining two strings of XML, using the While the History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||