於是我找解析,可能看起來像這樣的XML文件:解析不同父元素下相同類型的XML元素的模式?
<Locations>
<Location Name="California">
<Location Name="Los Angeles">
<Person Name="Harrison Ford"/>
</Location>
</Location>
</Locations>
<People>
<Person Name="Jake Gyllenhaal" Location="Los Angeles"/>
</People>
所以我建立的地點和人員名單。作爲一項商業規則,「人」必須與「地點」相關聯,但這可以通過以下兩種方式之一來完成。可以將它們列爲位置元素的子元素,以便他們可以採用該父級位置,或者在People元素下列出時明確列出它們。現在我處理它是這樣的(沒有任何錯誤檢查)。
public class Parser
{
public void Parse(XElement xmlRoot)
{
IList<Location> locations = new List<Location>();
IList<Person> people = new List<Person>();
var locationParser = new LocationParser();
locations = locationParser.ParseLocations(xmlRoot.Element("Locations"), people);
var peopleParser = new PeopleParser();
people = peopleParser.ParsePeople(xmlRoot.Element("People"), locations);
// Do stuff with XML read objects.
}
}
public class PeopleParser
{
public IList<Person> ParsePeople(XElement peopleRoot, IList<Location> locations)
{
var xPeople = peopleRoot.Elements("Person");
var people = new List<Person>();
foreach (var person in xPeople)
{
var locationName = person.Attribute("Location").Value;
var location = locations.First(loc => loc.Name.Equals(locationName));
people.Add(this.ParsePerson(person, location));
}
return people;
}
public Person ParsePerson(XElement person, Location location)
{
var personName = person.Attribute("Name").Value;
return new Person(personName, location);
}
}
public class LocationParser
{
PeopleParser peopleParser = new PeopleParser();
public IList<Location> ParseLocations(XElement locationRoot, IList<Person> people)
{
var xLocations = locationRoot.Elements("Location");
var locations = new List<Location>();
foreach (var location in xLocations)
{
locations.Add(this.ParseLocation(location, people));
}
return locations;
}
public Location ParseLocation(XElement xLocation, IList<Person> people)
{
var children = new List<Location>();
foreach (var subLocation in xLocation.Elements("Location"))
{
children.Add(this.ParseLocation(subLocation, people));
}
var newLocation = new Location(xLocation.Attribute("Name").Value, children);
foreach (var xPerson in xLocation.Elements("Person"))
{
people.Add(peopleParser.ParsePerson(xPerson, newLocation));
}
return newLocation;
}
}
}
此代碼是我「醜」,這只是東西變得更依賴XML類型添加了很多醜陋的一個簡單的例子。這是否如此好,還是有一種方法可以重寫,以更好地分離關注點?
我不明白你的問題。或者爲什麼一個人被列爲兩種不同的方式之一,但基本意義相同。 – 2014-12-11 00:11:16
問題是,這可以解析'更好'說例如讓PeopleParser離開LocationParser。至於爲什麼可以用多種方式定義一個人只是添加選項。我主要是在構建我自己的解析器來尋找已經存在的東西,所以我必須遵循創建者的約定。在Wix工具集中查找示例,其中XML元素(如組件)可以在各種不同的元素下聲明。 – Thermonuclear 2014-12-11 00:28:46
您需要在名稱旁邊的Location對象中存儲什麼信息?路徑也很重要(例如:加州/洛杉磯)? – alexm 2014-12-11 00:49:40