Date parsed: 07/10/2007 07:51:17
Date: Sun, 07 Oct 2007 14:51:17 -0700
On Oct 7, 9:57 pm, Flyguy <fly...@nospam.nospam> wrote:
> I am unable to select a specific XmlElement from my xml document. I have an
> xml file with the following data:
>
> <?xml version="1.0" encoding="utf-8"?>
> <my_data>
> <dogs>
> <dog id="benji" breed="mutt">
> <dog id="Lassie" breed="collie">
> </dogs>
> </my_data>
>
> If I create an XmlDataSource using the xml file the following line of code
> will return null. How can I get this to work?
>
> XmlElement myDog = MyXmlDataSource.GetXmlDocument().GetElementById("benji");
GetElementById requires a DTD or an XML schema to indicate which
attribute has to be used as an id. In your case you need to define the
following
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE my_data [
<!ELEMENT my_data ANY>
<!ELEMENT dogs ANY>
<!ELEMENT dog EMPTY>
<!ATTLIST dog id ID #REQUIRED>
<!ATTLIST dog breed CDATA #REQUIRED>
]>
<my_data>
<dogs>
<dog id="benji" breed="mutt" />
<dog id="Lassie" breed="collie" />
</dogs>
</my_data>
Then it would work with your code. For more information about
GetElementById Method please refer MSDN:
http://msdn2.microsoft.com/en-us/library/system.xml.xmldocument.getelementbyid.aspxYou can also do another method, e.g. SelectSingleNode, in this case it
would work without changes in XML
XmlNode myDog = MySource.GetXmlDocument().SelectSingleNode("//
*[@id='benji']");
Hope it helps