c# XML解析-获取子节点的属性
本文关键字:子节点 属性 获取 XML 解析 | 更新日期: 2023-09-27 18:11:26
我有这样的XML:
<tileset firstgid="1" name="simple_tiles" tilewidth="32" tileheight="32" tilecount="16" columns="8">
<image source="../Users/mkkek/Pictures/rpg/default_tiles_x.png" width="256" height="64"/>
</tileset>
当我在tileset
节点时,我如何访问image
节点及其source
属性?我的代码如下:
public void LoadMaps(ContentManager content)
{
Dictionary<string, string> mapsToLoad = InitMapsToLoad();
foreach (KeyValuePair<string, string> mapToLoad in mapsToLoad)
{
Map map = new Map();
map.Name = Path.GetFileNameWithoutExtension(mapToLoad.Value);
reader = XmlReader.Create("Content/" + mapToLoad.Value);
while(reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{
switch(reader.Name)
{
case "tileset":
if(!Tilesets.Any(ts => ts.Name == reader.GetAttribute("name")))
{
// handling the image node here
}
break;
}
}
}
}
}
我通常更喜欢使用LINQ to XML,因为我发现它的API比XmlReader更容易使用,这是两种技术之间的比较。
如果您所需要的只是从image元素获取源属性值,这可以很容易地实现:
var doc = XDocument.Load("something.xml");
var root = doc.DocumentElement;
var imageElements = root.Elements("image").ToList();
foreach (var imageElement in imageElements)
{
var sourceAttribute = imageElement.Attribute("source");
var sourceValue = sourceAttribute.Value;
//do something with the source value...
}
关于LINQ to XML中的基本查询的更多信息请参阅此处。
我建议创建一些表示Xml结构的类,如:
[XmlRoot(ElementName = "image")]
public class Image
{
[XmlAttribute(AttributeName = "source")]
public string Source { get; set; }
[XmlAttribute(AttributeName = "width")]
public string Width { get; set; }
[XmlAttribute(AttributeName = "height")]
public string Height { get; set; }
}
[XmlRoot(ElementName = "tileset")]
public class Tileset
{
[XmlElement(ElementName = "image")]
public Image Image { get; set; }
[XmlAttribute(AttributeName = "firstgid")]
public string Firstgid { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "tilewidth")]
public string Tilewidth { get; set; }
[XmlAttribute(AttributeName = "tileheight")]
public string Tileheight { get; set; }
[XmlAttribute(AttributeName = "tilecount")]
public string Tilecount { get; set; }
[XmlAttribute(AttributeName = "columns")]
public string Columns { get; set; }
}
然后在某些实用程序类中添加以下方法:
public static T DeserializeFromXml<T>(string xml)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
var serializer = new XmlSerializer(typeof(T));
T entity;
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
entity = (T)serializer.Deserialize(reader);
}
return entity;
}
现在,您将能够使用以下代码访问Image对象:
Tileset tileset=DeserializeFromXml<Tileset>(yourXmlContent);
// now you can access the image from the tileset instance 'tileset.Image.Source'
差不多完成了。将此添加到您的代码中。
// handling the image node here
if (reader.ReadToDescendant("image"))
{
string source = reader.GetAttribute("source");
}