Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XML parsing: how to differentiate between self-closing tag and other tags?

Tags:

c#

xml-parsing

I'm using the "XmlTextReader" object in ASP.NET C# to read an xml file. In my code I really need to differentiate between self-ending tags like

<img src="something" />

and ones that has elements inside and need ending tags like:

<div class="anything">
    <img src="something" />
</div>

I've tried the HasValue method but it didn't work out well for me. Is there any other way to detect that BEFORE actuallcy reading through the element?

I can use the ReadElementContentAsString() method, but I don't really wanna do that. I need to know whether there's something inside before going inside. or at least be able to go back.

UPDATE This is how I'm reading my code

        reader.MoveToAttribute("id"); //I know all attributes
    if (reader.ReadAttributeValue())
        this.idField = reader.Value;


    reader.MoveToElement();
    bool goOn = true;
    while (goOn)
    {
        reader.Read();
        switch (reader.NodeType)
        {
            case XmlNodeType.Element:
                switch (reader.Name)
                {

                    case "div":
                        DivType newDivTypeItem = new DivType(reader);
                        this.itemsField.Add(newDivTypeItem);
                        this.itemsElementNameField.Add(ItemsChoiceType17.div);
                        break;
                    other cases...
                }
                break;
            case XmlNodeType.Text:
                this.textField.Add(reader.Value);
                break;
            case XmlNodeType.EndElement:
                goOn = false;
                break;
        }
    }
like image 553
himura Avatar asked Oct 28 '25 08:10

himura


1 Answers

Is the IsElementEmpty property what you want? How exactly are you reading your document such that this is coming up?

like image 141
Etan Reisner Avatar answered Oct 29 '25 22:10

Etan Reisner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!