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

dotnet xml : Lost in XPath


Tom Clement
5/25/2004 4:17:57 PM
I really believe it's possible to do what I want with a SelectNodes() XPath
query, but I'm lost. Any help would be appreciated. Suppose you have an
XML document (like a WordProcessingML file) that has a bunch of elements
embedded in it that conform to a schema, but each schema-defined
parent/child relationship can have (an arbitrary number of) intervening
elements from another namespace. I'm trying to do something simple, find
all "children" (considering only my namespace) of a particular node. For
example suppose you have something like:

<w:wordDocument xmlns:w="http://theirs" xmlns:ns1="http://mine" >
....
<w:body>
<wx:sect>
<ns1:ReportData>
<w:pPr>
<w:jc w:val="center" />
</w:pPr>
<w:p />
<ns1:Solution>
<w:p />
<ns1:Requirements/>
<w:p />
</ns1:Solution>
<w:p />
<ns1:Path/>
</ns1:ReportData>
</wx:sect>
</w:body>
</w:wordDocument>

Suppose I have an XmlElement corresponding to the <ns1:ReportData> element.
I know I can get all ns1: descendants using SelectNodes("//ns1:*", ...).
But how in the world can I qualify this so that I only get the "child" (sort
of) descendants (within my namespace) which are <ns1:Solution> and
<ns1:Path> but not nodes that are under one of those, like
<ns1:Requirements>.

Thanks for your help with this puzzler.
Tom Clement
Apptero, Inc.

Dare Obasanjo [MSFT]
5/26/2004 4:43:40 PM
What you are trying to do is sometimes called subtree pruning or filtering
and is beyond the capabilities of XPath. I'd suggest using XSLT to solve
this problem.

--
This posting is provided "AS IS" with no warranties, and confers no rights.

[quoted text, click to view]

Tom Clement
5/26/2004 8:57:51 PM
Dare,
Thank you for your response. I think I got a bit carried away with trying
to do it all in XPath since I actually have C# to work with. FYI, I just
wrote a function that served my narrow purposes.

private void GetChildElementsFromNamespace(XmlNode node, ArrayList tagNodes,
string ns)
{
foreach(XmlNode child in node.ChildNodes)
{
XmlElement elChild = child as XmlElement;
if( elChild != null ) // Do nothing with attributes etc.
{
if( elChild.NamespaceURI == ns )
tagNodes.Add(elChild);
else // Only recurse if this isn't in our namespace
GetChildElementsFromNamespace(elChild, tagNodes, ns);
}
}
}

Tom

[quoted text, click to view]

AddThis Social Bookmark Button