2014-05-14 65 views
0

我有一个XML格式的Word文档具有多个条目,像这样:如何提取所有书签的名称在Word XML文档

<aml:annotation aml:id="0" w:type="Word.Bookmark.Start" w:name="CustomerName"/> 

我想找回这些的集合,但看不到如何通过

foreach (XElement ann in doc.Root.Descendants(aml + "annotation")) 

换句话说,我可以得到所有注释,但不能看到如何筛选以检索书签。该命名空间amlw声明这样

XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; 
    XNamespace aml = "http://schemas.microsoft.com/aml/2001/core"; 

可能有人给我推一下吗?


我解决了问题如下

 XNamespace w = doc.Root.GetNamespaceOfPrefix("w"); 
     XNamespace aml = doc.Root.GetNamespaceOfPrefix("aml"); 

     foreach (string bookm in doc.Descendants(aml + "annotation") 
            .Where(e => e.Attributes(w + "type") 
            .Any(a => a.Value == "Word.Bookmark.Start")) 
            .Select(b => b.Attribute(w + "name").Value)) 
     { 
      ... 
     } 

回答

1
var names = from a in doc.Root.Descendants(aml + "annotation")) 
      where (string)a.Attribute(w + "type") == "Word.Bookmark.Start" 
      select (string)a.Attribute(w + "name"); 

lambda语法:

doc.Root.Descendants(aml + "annotation") 
     .Where(a => (string)a.Attribute(w + "type") == "Word.Bookmark.Start") 
     .Select(a => (string)a.Attribute(w + "name")) 
+0

你说得对,我想要的是一个名字的集合,但我的困难是只获得“Word.Bookmark.Start”元素。还有其他注释不符合资格。 –

+0

@HughJones只需添加过滤器即可。更新我的回答 –

+0

这两种技术都会返回一个空列表。如果我拿出'where'条款,他们都会返回一个50个空值的列表。这实际上就是我用自己的努力去做的。我的问题是,我认为,我不知道如何处理嵌入到属性中的命名空间,例如'w:type =“Word.Bookmark.Start”' –

0

这个解决方案不是为XML,但也许可以帮助你。

System.Collections.Generic.IEnumerable<BookmarkStart> BookMarks = wordDoc.MainDocumentPart.RootElement.Descendants<BookmarkStart>(); 
foreach (BookmarkStart current in BookMarks) 
{ 
    //Do some... 
} 
相关问题