XML-parsing in WinRT

2019-09-08 03:32发布

问题:

If I have a XML-document like this

<Doc>
   <File>
      <ObjectID></ObjectID>
   </File>
</Doc>

And it sometimes can look like this

<Doc>
   <Name />
   <File>
      <ObjectID></ObjectID>
   </File>
</Doc>

How can I get the File-elements?
They are not always on the same level, sometimes they can be on the root-level
There could also be times, when it is placed multiple times in the Document (but then they are at the same level)

UPDATE

The <File>-element can also have <File> elements below, which should not be parsed like this

<Doc>
   <Name />
   <File>
      <ObjectID></ObjectID>
      <RelatedTo>
         <File></File>
      </RelatedTo>
   </File>
</Doc>

In which case the result should be

<File>
   <ObjectID></ObjectID>
   <RelatedTo>
      <File></File>
   </RelatedTo>
</File>

回答1:

With s being the string which contains your XML code:

var document = XDocument.Parse(s);
var fileElements = document.Descendants("File").
                       ToArray();

Note that you won't get one single element but an array. In case there's only one in your document, then the array will have just one element.

The above approach will work even if the File elements are children of other elements, but I'm not sure what you meant by them being at "root level". Isn't that the case that you brought us?

EDIT: To adapt it to the author's edit:

var elementName = "File";
var firstFileElement = document.Descendants(elementName).
    First();
var fileElements = firstFileElement.Parent.Elements(elementName).
    ToArray();