XML element and namespace

I have the following method for parsing XMLElements:

DisplayMessages(XElement root)
{
  var items = root.Descendants("Item");
  foreach (var item in items)
  {
     var name = item.Element("Name");
     ....
  }
}

In debug mode, I can see the root as XML as follows:

<ItemInfoList>
  <ItemInfo>
    <Item>
      <a:Name>item 1</a:Name>
      ...
    <Item>
    ...

and var is null (I expect to get "element 1"). I tried using "a: Name" but threw an exception ("character: cannot be used in name"). I'm not sure if I need to set the namespace in the root XElelement or not. All xml node as root must be in the same namespace.

I am new to XElement. In my codes, item.Element ("Name") will get its child values ​​for the node "Name", right?

+3
source share
4 answers

, . :

static void DisplayMessages(XElement root)
{
    var items = root.Descendants(root.GetDefaultNamespace() + "Item");
    foreach (var item in items)
    {
        var name = item.Element(item.GetNamespaceOfPrefix("a") + "Name");
        Console.WriteLine(name.Value);
    }
}

, + XNamespace, : XNamespace.Addition.

+4

"a" :

<Root a:xmlns="http:///someuri.com">
...
</Root>

, , LINQ to XML:

XNamespace a = "http:///someuri.com"; // must match declaration in document
...
var name = item.Element(a + "Name");

EDIT:

:

XNamespace defaultNamespace = document.Root.GetDefaultNamespace();
// XNamespace.None is returned when default namespace is not explicitly declared

:

var declarations = root.Attributes().Where(a => a.IsNamespaceDeclaration);

, , , . , , , XML, .

+3

XNames, . XNamespace , . XName .

0

XML, , . ( , , , " " , ).

XNamespace XElements, MSDN: Element(), XName

0

Source: https://habr.com/ru/post/1718149/


All Articles