2016-03-07 87 views
0

這裏是我的代碼解析值.NET C#

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 

我無法獲得,因爲不同的命名空間可能的的Uid,同樣適用於AV:Canvas.Top

如何獲取這些屬性?

-TIA

回答

1

串聯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; 
1

試試這個

 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; 
2

首先,添加全部namespaces

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

現在,如果您想檢查屬性和節點而不考慮命名空間,那麼您可以簡單地訪問每個節點,然後遍歷其屬性以查找值。

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

只要你添加路徑要在SelectSingleNode參觀和你namespaces聲明你應該能夠通過任何節點運行,並得到你想要的任何值。