Locate the first text node at any level below the given XML node. - CSharp System.Xml

CSharp examples for System.Xml:XML Node

Description

Locate the first text node at any level below the given XML node.

Demo Code

/*/* ww  w  .ja  v a  2s.  c o m*/
 * ====================
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2008-2009 Sun Microsystems, Inc. All rights reserved.     
 * 
 * The contents of this file are subject to the terms of the Common Development 
 * and Distribution License("CDDL") (the "License").  You may not use this file 
 * except in compliance with the License.
 * 
 * You can obtain a copy of the License at 
 * http://IdentityConnectors.dev.java.net/legal/license.txt
 * See the License for the specific language governing permissions and limitations 
 * under the License. 
 * 
 * When distributing the Covered Code, include this CDDL Header Notice in each file
 * and include the License file at identityconnectors/legal/license.txt.
 * If applicable, add the following below this CDDL Header, with the fields 
 * enclosed by brackets [] replaced by your own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * ====================
 */
using System.Text;
using System.Xml;
using System;

public class Main{
        /// <summary>
        /// Locate the first text node at any level below the given node.
        /// </summary>
        /// <remarks>
        /// If the
        /// ignoreEmpty flag is true, we will ignore text nodes that contain only
        /// whitespace characteres. <p /> Note that if you're trying to extract
        /// element content, you probably don't want this since parser's can break up
        /// pcdata into multiple adjacent text nodes. See getContent() for a more
        /// useful method.
        /// </remarks>
        private static XmlText FindText(XmlNode node, bool ignoreEmpty)
        {

            XmlText found = null;

            if (node != null)
            {

                if (node.NodeType == XmlNodeType.Text
                        || node.NodeType == XmlNodeType.CDATA)
                {

                    XmlText t = (XmlText)node;
                    if (!ignoreEmpty)
                        found = t;
                    else
                    {
                        String s = t.Data.Trim();
                        if (s.Length > 0)
                            found = t;
                    }
                }

                if (found == null)
                {

                    for (XmlNode child = node.FirstChild; child != null
                            && found == null; child = child.NextSibling)
                    {

                        found = FindText(child, ignoreEmpty);
                    }
                }
            }

            return found;
        }
}

Related Tutorials