knowme
knowme

Reputation: 417

converting xml file to html

i have a task to do. i need to convert xml to html file. i check the tag and then write the html file with the tag based from the xml file. Like if i found <BookHeader> i write <h1> in the html file.

i have this

layout of xml

<BookHeader>
    <AuthorGroup>
      <Author >
        <AuthorName >
          <GivenName>Juanita</GivenName>
          <FamilyName>Gomez</FamilyName>
        </AuthorName>
        <Contact>
          <Email>[email protected]</Email>
        </Contact>
      </Author>

    </AuthorGroup>
  </BookHeader>

  <ChapterInfo >
      <ChapterID>1</ChapterID>
      <ChapterNumber>Chapter 1</ChapterNumber>

      <ChapterTitle Language="En">Just some Title</ChapterTitle>


      <ChapterHistory>
        <RegistrationDate>
          <Year>2020</Year>
          <Month>8</Month>
          <Day>18</Day>
        </RegistrationDate>
      </ChapterHistory>

    </ChapterInfo>

i have this code in c#

i read the xml element one by one. so far the code below does is print all elements and its content

but what i want to do is if the element name is <ChapterHistory> the program will not read the content of the tag up to its closing tag

so the program will not read the tag

<RegistrationDate>
              <Year>2020</Year>
              <Month>8</Month>
              <Day>18</Day>
            </RegistrationDate>

how can i do this? thank you so much. i have a hard time doing this

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(myString));

            while (rdr.Read())
            {

                switch (rdr.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.WriteLine("<" + rdr.Name + ">");

                        break;
                    case XmlNodeType.Text:
                        Console.WriteLine(rdr.Value);

                        break;
                    case XmlNodeType.EndElement:
                        Console.WriteLine("...");
                        break;
                }
                count++;

            }

Upvotes: 0

Views: 949

Answers (1)

Stefan Hegny
Stefan Hegny

Reputation: 2187

NB. I don't know C# so I can only try to explain in plain language.

You could simply map the values, e.g. if rdr.Name is BookHeader then write <h1> etc.pp. If you have access to the rdr.Name in the EndElement case you can simply close the same mapped value like </h1>. Otherwise you'd have to keep track of the open elements yourself and close the innermost.

About the problem to skip some of the xml structure see my comment to the question.

Note that I agree with some other commentators that this problem generally is more suited for an XSLT solution.

Upvotes: 1

Related Questions