2017-02-21 170 views
0

我有一个XML文件,我试图用C#读取。
我已经能够得到很多,但我遇到了一个特定的问题。无法获取XML属性

这是XML文件:

<map version="1.0" orientation="orthogonal" renderorder="right-down" width="60" height="40" tilewidth="16" tileheight="16" nextobjectid="4" source="test.png"> 
    <tileset firstgid="1" name="test" tilewidth="16" tileheight="16" tilecount="240" columns="24"> 
    <image source="../test.png" trans="ffaec9" width="388" height="163"/> 
    </tileset> 
</map> 

我有一些困难,试图获得这些属性都在<image>标签。我需要sourcewidth

我在地图上,但不使用

tileSize = int.Parse(doc.DocumentElement.GetAttribute("tilewidth")); 

我怎样才能从<image>sourcewidth的图像数据吗?

+0

我加了一个闭合''标签的XML,以便让你的XML格式良好。 – zx485

回答

1

您可以轻松地使用LINQ和XDocument & XElement得到你需要的值:

var xDoc = XDocument.Parse("<my xml/>"); 
var tileset = xDoc.Element("map").Element("tileset"); 
var image = tileset.Element("image"); 

var tileWidth = int.Parse(tileset.Attribute("tilewidth").Value); 
var source= image.Attribute("source").Value; 
var width = int.Parse(image.Attribute("width").Value); 
0

你可以看看XPath。这里有一些例子,online demo

string source = doc.SelectSingleNode("/map/tileset/image/@source").Value; // "../test.png" 
string width = doc.SelectSingleNode("//image/@width").Value;    // "388" 
string height = doc.SelectSingleNode("//@height[last()]").Value;   // "40"