.NET edit specific XML nodes after finding them with XmlTextReader
Certain nodes in an XML file need to be edited.
I collected them with an XmlTextReader. If I come across a Remark node, I skip to the next node. If I come across the other specified nodes and they don't start with a certain pattern, I put them in a collection.
List<KeyValuePair<string, string>> Data = new List<KeyValuePair<string, string>>();
string key = "";
string value = "";
reader = new XmlTextReader(file);
switch (reader.NodeType)
{
case XmlNodeType.Element:
switch (reader.Name)
{
case "Remark":
reade开发者_JS百科r.Skip();
break;
case "DataTableColumn":
case "Label":
case "Button":
case "PopupPanel":
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "ID":
key = reader.Value;
break;
case "Header":
case "Caption":
value = reader.Value;
break;
}
}
if (!value.StartsWith("@"))
{
Data.Add(new KeyValuePair<string, string>(key, value));
}
break;
}
break;
}
Now at this point I have modified the values of all items in the collection, and I want to update the original file. What is the best way to do this?
Is there any reason you don't use XSLT for this? It seems like it would be the most appropriate technology for doing this.
If you need to modify a XML file, I recommend you use XDocument, providing the file is small enough to be loaded into memory.
Otherwise use XmlReader for reading combined with XmlWriter for writing, or XSLT.
First of all, don't use new XmlTextReader()
. It's been deprecated since .NET 2.0. Use XmlReader.Create()
instead.
Second of all, an XmlReader is a read-only, forward-only cursor. You can't go back to write out the modified nodes.
You should use LINQ to XML, or an XmlDocument to do this sort of work.
精彩评论