简体   繁体   中英

parse XML nodes with the name “object” in XDocument in C#

my problem is as follows: I want to parse a xml-file created with Tiled Map Editor where I inserted one objectlayer (for collision objects). But unfortunately, Tiled named the node in the xml-file "objectgroup" and its descendants "object"

<objectgroup name="solidObjects" width="100" height="100">
 <object gid="265" x="16" y="35"/>
 <object gid="265" x="66" y="36"/>
</objectgroup>

I am trying to do something like

XDocument doc = XDocument.Load("pathtoFile\sourcefile.xml");
List<Rectangle> objectList = new List<Rectangle>();

foreach (var object in doc.Element("objectgroup").Descendants("object"))
{ objectList.Add(objectRectangle); }

But since "object" is a protected word in c#, it doesn't work. Any tips how to handle this problem the easiest way?

If you absolutely, definitely have to use object as your variable name (which is not recommended), then you can prefix it with an @ sign:

foreach (var @object in doc.Element("objectgroup").Descendants("object")) {
    objectList.Add(@object);
}

The @ sign prefix allows identifiers in your code to use reserved words as their names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM