现在,我发现我遗失了一件物品。 我想这样做;
1 Boo1 // "1" is from <sdl:seg id="1">
2 Boo2
3 Boo3
...
..
.
从这里开始。
<xliff xmlns:sdl="http://sdl.com/FileTypes/SdlXliff/1.0">
<sdl:seg-defs>
<sdl:seg id="1">
<sdl:value key="Hash">Foo1</sdl:value>
<sdl:value key="Created">Boo1</sdl:value>
我试图这样做..
XDocument myDoc = XDocument.Load(myPath);
Dictionary<string, XElement> myDic = myDoc.Descendants()
.Where(x => x.Name.LocalName == "seg")
.Select((myValue, myKey) => new { myKey, myValue })
.ToDictionary(x => x.Attribute("id").Value, x => x); // Error at .Attribute(
List<string> myList = myDic
.Where(x => ((x.Value).Name.LocalName == "value")
&& ((string)(x.Value).Attribute("key") == "Created"))
.Select(x.Key + " " + (string)x.Value);
MessageBox.Show(string.Join("\n", myList));
感谢。
答案 0 :(得分:1)
var q = from elem in myDoc.Descendants()
where elem.Name.LocalName == "seg"
from sub in elem.Descendants()
where sub.Name.LocalName == "value" && sub.Attribute("key").Value == "Created"
select new
{
Id = elem.Attribute("id").Value,
Created = sub.Value
};
正确的命名空间处理:
XNamespace sdl = "http://sdl.com/FileTypes/SdlXliff/1.0";
var q = from elem in myDoc.Descendants()
where elem.Name == sdl + "seg"
from sub in elem.Descendants()
where sub.Name== sdl + "value" && sub.Attribute("key").Value == "Created"
select new
{
Id = elem.Attribute("id").Value,
Created = sub.Value
};
要格式化它:
var msg = String.Join("\n", q.Select(item => $"{item.Id} {item.Created}"));
答案 1 :(得分:1)
试试这个
Dictionary<string, List<XElement>> myDic = myDoc.Descendants()
.Where(x => x.Name.LocalName == "seg")
.GroupBy(myKey => (string)myKey.Attribute("id"))
.ToDictionary(x => x.Key, y => y.Descendants().Where(z => z.Name.LocalName == "value").ToList());
Dictionary<string, Dictionary<string,string>> myDic2 = myDoc.Descendants()
.Where(x => x.Name.LocalName == "seg")
.GroupBy(myKey => (string)myKey.Attribute("id"))
.ToDictionary(x => x.Key, y => y.Descendants().Where(z => z.Name.LocalName == "value")
.GroupBy(z => (string)z.Attribute("key"), a => (string)a)
.ToDictionary(z => z.Key, a => a.FirstOrDefault()));