简体   繁体   English

使用多个名称空间.net C#从XML解析值

[英]Parsing values from XML using multiple namespaces .net C#

Here is my code 这是我的代码

 String MyXml = "<av:Button Name="btn_1" Width="80" Height="25" x:Uid="btn_1" av:Canvas.Left="168.1" av:Canvas.Top="95.1" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">My Button Content</av:Button>";

    XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable());
    mngr.AddNamespace("av", "http://www.w3.org/2001/XMLSchema-instance");

    XmlParserContext parserContext = new XmlParserContext(null, mngr, null, XmlSpace.None);

    XmlTextReader txtReader = new XmlTextReader(MyXml, XmlNodeType.Element, parserContext);

    var doc = XElement.Load(txtReader);

    var name = doc.Attribute("Name").Value;
    var width = doc.Attribute("Width").Value; 
    var Uid   = doc.Attribute("Uid").Value; // Not Working

I am unable to get the Uid because of different namespace probably, same goes for av:Canvas.Top . 由于名称空间不同,我无法获得Uidav:Canvas.Top也是如此

How to get these attributes? 如何获得这些属性?

-TIA -TIA

First, add all the namespaces 首先,添加所有namespaces

    XmlNamespaceManager manager= new XmlNamespaceManager(new NameTable());
    mngr.AddNamespace("av", "http://www.w3.org/2001/XMLSchema-instance");
    mngr.AddNamespace("x", "url_for_x");

Now, if you want to check for attributes and nodes regardless of the namespace you could simply visit each node and then loop through its attributes to find out the value. 现在,如果您要检查属性和节点,而不管名称空间如何,您只需访问每个节点,然后遍历其属性以找出值即可。

    XmlNode uuidNode = xmldoc.SelectSingleNode("/namespace:node", manager);
    if (uuidNode.Attributes != nul)
      foreach(XmlAttribute oAttribute in uuidNode.Attributes)
        if (oAttribute == "UUID")
          name = oAttribute.Value;

As long as you add the path you want to visit in SelectSingleNode and your namespaces are declared you should be able to run through any node and get any value you want. 只要在SelectSingleNode添加要访问的路径并且声明了namespaces ,您就应该能够在任何节点上运行并获取所需的任何值。

Try this 尝试这个

        XNamespace xlink = "http://schemas.microsoft.com/winfx/2006/xaml";
        var name = doc.Attribute("Name").Value;
        var width = doc.Attribute("Width").Value;
        var Uid = doc.Attribute(xlink + "Uid").Value;

Concatenate MyXml with xmlns:av="anyNameSpaceName" and then you can access it with, 将MyXml与xmlns:av =“ anyNameSpaceName”连接起来,然后您可以使用它进行访问,

  String MyXml = "<av:Button Name=\"btn_1\" Width=\"80\" Height=\"25\" x:Uid=\"btn_1\" av:Canvas.Left=\"168.1\" av:Canvas.Top=\"95.1\" xmlns:av=\"anyNameSpaceName\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">My Button Content</av:Button>";
  XNamespace ns = "anyNameSpaceName";
  var Canvat_Top= doc.Attribute(ns + "Canvas.Top").Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM