I am trying to Parse XML object with two namespaces inside the file.
<xliff srcLang="en" version="23.0"
xmlns="asd:asd:asd:asd:xliff:document:23.0"
xmlns:mda="asd:asd:asd:asd:xliff:document:23.0">
<file id="f"
original="someUrl">
<unit id="1" name="air">
<mda:data>
<mda:group category="attributes">
<mda:meta type="id">Color</mda:meta>
<mda:meta type="abbr">I_AI_LOW</mda:meta>
<mda:meta type="type">Message</mda:meta>
</mda:group>
</mda:data>
<segment>
<source>Too many messages for 1 minute</source>
</segment>
</unit>
</file>
</xliff>
I want to take the value from unit id="1" name="air" from property name, "mda:meta type="type" property type and source>Too many messages for 1 minute - property segment. I want to assign their value to other properties, so basically to extract their value.
My code now is:
xliff = XDocument.Load(Path.GetFullPath(filePath));
var ns = xliff.Root!.Name.Namespace;
var elements = xliff.Descendants()
.Elements(ns "unit").ToList();
//this part not working
XElement tempElement = elements.Descendants(XName.Get("mda:metadata",
ns.ToString())).FirstOrDefault()!;
I know that somehow I have to access the second namespace, but I don't know how to do it. Any help here will be appreciated.
CodePudding user response:
Try using XNamespace
and LINQ
XNamespace ns1 = "asd:asd:asd:asd:xliff:document:23.0";
XNamespace ns2 = "asd:asd:asd:asd:xliff:document:23.0";
var type_value = xliff.Descendants(ns1 "unit")
.Descendants(ns2 "meta")
.Where(x => (string)x.Attribute("type") == "type")
.Select(y => y.Value)
.FirstOrDefault()
.ToString();
OR (to get all values to list)
var elements = xliff.Descendants(ns1 "unit")
.Descendants(ns2 "meta")
.Where(x => (string)x.Attribute("type") == "type")
.Select(y => y.Value.ToString())
.ToList();
OR (to get source from segment)
var nameSegment = xliff.Descendants(ns1 "unit")
.Descendants(ns1 "segment")
.Select(x => x.Element(ns1 "source").Value)
.ToList();
CodePudding user response:
Try following :
XDocument xliff = XDocument.Load(Path.GetFullPath(filePath));
XNamespace ns = xliff.Root.GetDefaultNamespace();
XNamespace nsMda = xliff.Root.GetNamespaceOfPrefix("mda");
List<XElement> elements = xliff.Descendants(ns "unit").ToList();
//this part not working
List<XElement> metaData = elements.Descendants(nsMda "metadata").ToList();