Search
Write a publication
Pull to refresh

Работа с XML в Silverlight2

Известно, что XML (Extensible Markup Language) — это замечательный формат для обмена структурированными данными. В данной статье, я бы хотел поделиться опытом работы с XML средствами Silverlight, по средствам объекта XmlReader.

Для начала создадим простой xml-файл:
<?xml version="1.0" encoding="utf-8" ?>
<ImageTree>
<Area name="grass">
<Image name="Normal Grass">grass1.png</Image>
<Image name="Dry Grass">grass2.png</Image>
<Image name="Mixed Grass">grass3.png</Image>
<Image name="Long Grass">grass4.png</Image>
</Area>
<Area name="tile">
<Image name="Brick">brick.png</Image>
<Image name="White Stone">stone.png</Image>
<Image name="Cracked Stone">crackedstone.png</Image>
<Image name="Black Brick">brick2.png</Image>
</Area>
</ImageTree>


В коде, представленном ниже можно отметить следующие моменты:
  • Для того чтобы открыть XML-файл, был использован WebClient-объект. Мы поместили файл с именем MapImages.xml в директорию ClientBin, директорию, которая содержит данные для дальнейшего чтения. Когда операция чтения будет завершена, произойдет вызов функции client_DownloadStringCompleted
  • Когда происходит чтение данных, идет простая проверка на тип узла.
  • При чтении элемента, значение атрибутов (и соответственно проверка на их наличие) было получено с помощью функции MoveToFirstAttribute().


public Page()
{
InitializeComponent();

Uri url = new Uri("MapImages.xml", UriKind.Relative);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(url);
}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
TreeViewItem areaItem = null;
TreeView tv = new TreeView();
TreeViewItem rootItem = new TreeViewItem();
rootItem.Header = "Images";
tv.Items.Add(rootItem);

StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
string imageName = String.Empty;
string areaName = String.Empty;
string fileName = String.Empty;

while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "Area")
{
if (true == reader.MoveToFirstAttribute())
{
areaName = reader.Value;
areaItem = new TreeViewItem();
areaItem.Header = areaName;
rootItem.Items.Add(areaItem);
}
}
else if (reader.Name == "Image")
{
if (true == reader.MoveToFirstAttribute())
{
imageName = reader.Value;
}
}
}
else if (reader.NodeType == XmlNodeType.Text)
{
fileName = reader.Value;
TreeViewItem imageItem = new TreeViewItem();
imageItem.Header = imageName;
imageItem.Tag = fileName;
if (null != areaItem)
areaItem.Items.Add(imageItem);
}
}
MainCanvas.Children.Add(tv); // Добавляем отображение.
}
}


image

В принципе ничего сложного и сверх ординарного нет…
Оригинал заметки
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.