0

I need your help. I am new to xml and need to get its attribute.

I have a mailbox(XmlNode) that is represented by the following InnerXml

<Mailbox Id="1" Name="[email protected]" />

I need to access the Id attribute using this piece of code

mailbox.Attribute["Id"].Value 

but it throws null reference exception. I haven't found any solution, as I can't make any changes to the

....mailbox.Attribute["Id"].Value .....part of code

can anyone help me?

3
  • The code you pasted represents the InnerXml or OuterXml? If it represents InnerXml, can you show what is in the OuterXml? Commented Jan 25, 2014 at 16:53
  • 3
    How do you acquire reference to mailbox? Commented Jan 25, 2014 at 16:53
  • (Withdrew my comment about case sensitivity on Id -- the font was misleading me; it looks like capital I was used.. In that case, I think Wiktor's question is on target: whatever mailbox represents, it isn't the <Mailbox> element shown above. (At least it probably isn't a namespace issue; attributes don't take default namepaces.) Commented Jan 25, 2014 at 18:57

2 Answers 2

1

Try using something like this piece of code

XmlReader reader = XmlReader.Create("Your_XML_Path");
string id;
  while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name == "Mailbox")
                {
                    id = reader.GetAttribute(0);
                }
            }
        }

Try this and let me know if u have any doubts or if this code doesnt work for you.

Sign up to request clarification or add additional context in comments.

Comments

0

Yeah, so I checked the OuterXml(actually didn't know there's a difference)

<Mailboxes><Mailbox Id="1" Name="[email protected]" />...

that was the reason why it didn't work. so now using

mailbox.SelectSingleNode("//Mailboxes/Mailbox").Attributes["Id"].Value

everything works correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.