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

dotnet xml : Getting the XML as text between two nodes


Pavils Jurjans
6/3/2004 1:20:41 PM
Hello,

I am interested in getting the XML contents as text between two XML elements
that I know follow each other. They could be in completely different levels,
but in XML file the first is above the second. Of course, a code could be
written that would first read InnerXml property of the start tag, extract
the opening parens <starttag>, then read all text nodes within, then do the
same with child nodes, then with start tag next siblings, then back up to
parent node and advance to next parent sibling, etc, etc, until the end node
is met. But that seems like exhaustive thing to do, and I am wondering if
there's some normal shorter way to do this. Now I know from XML-speak, that
there is such thing as XPointers, that allow some syntax to select a range
of characters. Perhaps it's kinda underdeveloped standard, as I don't see
much talk about using XPointers in .NET framework. Anyway, I don't really
care for standard, all I'd like to be able is to provide to method two
parameters - starting element node and ending element node, and it would
return string of non-self-contained XML what's between (including the start
element node itself)

Thanks,

-- Pavils

Some examples for reference

Input:

<blah>
<startTag>
<foo>
<too>
<endTag/>
</foo>
</foo>
</startTag>
</blah>

result:
<startTag>
<foo>
<too>

Input:

<blah>
<too>
<foo>
<too>
<startTag/>
</foo>
</foo>
</foo>
<endTag/>
</blah>

restult:
<startTag/>
</foo>
</foo>
</foo>

Magnus
6/3/2004 10:29:46 PM
Here is an example:
XmlDocument doc = null;
XmlElement nodeBeforeTxt = null;
try
{
doc = new XmlDocument();
doc.LoadXml("<Root><Element1/><Element2/></Root>");
nodeBeforeTxt = (XmlElement)doc.SelectSingleNode("Root/Element1");
doc.SelectSingleNode("Root").InsertAfter(doc.CreateTextNode("Text
between nodes"), nodeBeforeTxt);
MessageBox.Show(doc.OuterXml);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

"Pavils Jurjans" <pavils@mailbox.riga.lv> skrev i meddelandet
news:OtMw0QVSEHA.3988@tk2msftngp13.phx.gbl...
[quoted text, click to view]

Pavils Jurjans
6/4/2004 10:11:36 AM
Hello Magnus,

I am not sure if you understood me correctly...

I am talking not about content insertion, but content retrieval, as string.
I am looking for a code block that could be given two element nodes, and it
would return _string_ of all XML that's between those nodes. Imagine that
you open XML file in text editor, identify the starting node, then the
ending node, and select the text, including the starting node "<blah>" tag,
and ending the last character before the closing node's "<blah>" tag. So, I
want to extract this text and return it as string.

-- Pavils

AddThis Social Bookmark Button