如何提取xaml / xml文件的所有特定标签?

时间:2010-10-15 14:08:07

标签: c# xml regex xaml xpath

假设我需要使用C#在字典资源文件中提取所有实体画笔和线性渐变画笔。我该怎么做?请帮忙!

这个问题可以扩展为更加通用,例如“如何使用C#搜索文件时找到多行匹配?”

2 个答案:

答案 0 :(得分:1)

这是一个使用Linq to XML的简单示例,可以帮助您入门:

string xaml = @"
  <Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
        xmlns:basics=
         'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls'>
      <Canvas x:Name='BackgroundCanvas' Width='1200' Height='500' 
              Background='White'>
          <basics:Button x:Name='Cancel' Width='100' Height='40'  />
          <basics:Button x:Name='Save' Width='100' Height='40'  />
      </Canvas>
  </Grid>";

XDocument doc = XDocument.Parse(xaml);

// XAML uses lots of namespaces so set these up
XNamespace def = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XNamespace basics = "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls";
XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml";

// Find the button named "Cancel" on the canvas
var button = doc.Elements(def + "Grid")
        .Elements(def + "Canvas")
        .Elements(basics + "Button")
        .Where(a => (string)a.Attribute(x + "Name") == "Cancel")
        .SingleOrDefault();

if (button != null)
{
    // Print the width attribute
    Console.WriteLine(button.Attribute("Width").Value);
}

有两种方法可以使用XPath,但首先我们需要设置一个XmlNamespaceManager,它与XNamespace类的机制类似。以下两个示例都将使用此:

XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace("def", 
   "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
nsm.AddNamespace("basics", 
   "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls");
nsm.AddNamespace("x", 
   "http://schemas.microsoft.com/winfx/2006/xaml");

使用XPath查询XDocument,然后在“保存”按钮上更改Width属性:

XElement saveButtonXe = 
        ((IEnumerable)doc.
          XPathEvaluate("//def:Canvas/basics:Button[@x:Name = 'Save']", nsm))
          .Cast<XElement>()
          .SingleOrDefault();

if(saveButtonXe != null)
{
  // Set the Width value
  saveButtonXe.Attribute("Width").SetValue("250");
  Console.WriteLine(doc.ToString());
}

将XPath'old school'样式与XmlDocument

一起使用
// Remember to initialise the XmlNamespaceManager described above
XmlDocument oldSkool = new XmlDocument();
oldSkool.LoadXml(xaml);
XmlNode saveButtonNode = 
   oldSkool.SelectSingleNode("//def:Canvas/basics:Button[@x:Name = 'Save']", nsm);
if(saveButtonNode != null)
{
  Console.WriteLine(saveButtonNode.Attributes["Width"].Value);
}

答案 1 :(得分:0)

将文件加载到XDocument并使用它来查找匹配项。 Regexxml不是很好的匹配(双关语)。