Search code examples
c#xelement

Can I get the length of the values in a tag


I have an XML file that starts with:

<!DOCTYPE html>
<!-- This is a simple page with no bean -->
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
    <title>Combo boxes page</title>
</h:head>

What I'm doing in order to work on this file is:

XElement root = (XElement.Load(fileName, LoadOptions.SetLineInfo | LoadOptions.PreserveWhitespace));

Once I have the root, can I get the length of the text in it? (The HTML language...)


Solution

  • Do you want the length of the string starting with the opening html tag (<html...) to the closing html tag (</html>)?

    XElement root = (XElement.Load(fileName ,LoadOptions.SetLineInfo | LoadOptions.PreserveWhitespace));
    
    int htmlLength = root.ToString().Length;
    
    System.Diagnostics.Debug.WriteLine("length of string including html tags: " + htmlLength);
    

    Or do you want the length of the string between the html tags?

    String html = root.ToString();
    int indexOpeningTag = html.IndexOf(">")+1;
    String contentInHtmlTags = html.Substring(indexOpeningTag, html.IndexOf("</html>") - indexOpeningTag);
    
    System.Diagnostics.Debug.WriteLine("length of string between html tags: " + contentInHtmlTags.Length);