Groups | Blog | Home
all groups > dotnet xml > may 2004 >

dotnet xml : Problem using XmlTextReader and XmlTextWriter.


Pete
5/19/2004 10:42:32 PM
I'm trying to read an XML document and write out a slightly modified
version using the XmlTextWriter.
I'm basically trying to copy all the nodes exactly as they are read and
do some text manipulation on #text nodes of only certain named elements.

example

while (xmltextreader.Read())
{
if (xmltextreader.NodeType == XmlNodeType.Text)
{
string modified = xmltextreader.Value;
// manipulate string here
xmltextwriter.WriteString(modified);
}
else
{
// The dilemma is here!
xmltextwriter.WriteNode(xmltextreader, false);
}
}

The problem I face is that the WriteNode method of the XmlTextWriter
copies all of its children and this creates a problem for iterating
through all the nodes. I would like some way to pass some nodes through
to the writer with no changes.

Does anyone have a solution for performing this kind of simple
processing?

Thanks,

Paul Petrov
5/20/2004 10:36:02 PM
Pete

You can do switch on NodeType for all types of nodes XmlReader handles. It's not much, only 18 case statements and you will have more granular control of the output xml in future. You can use WriteNode() if you absolutely sure current node doesn't have any children you need to modify like if(reader.Name != "ThisNodeHasSomeSuffToModify") writer.WriteNode(reader, false).

Pete
5/21/2004 9:08:05 AM
Thanks Paul,

I wondered if there was a way to do this without a lengthy switch block.
Have you seen any examples of this type of code that has been tested and
ready to use? Just curious. I'm still debating whether it would be more
robust to do this using xslt instead.

In any case, thanks for the suggestion.

Pete


[quoted text, click to view]
Yan Leshinsky
5/21/2004 11:21:14 AM
You can create your own XmlWriter based on XmlTextWriter, overrite
WirteNode; do what you have to do and/or call base.WriteNode.
Yan

[quoted text, click to view]

AddThis Social Bookmark Button