我正在使用Linq to Xml来操作openXml文档。更准确地说,我正在尝试读取和写入文档的自定义属性。我目前在向XElement添加前缀时遇到了问题。我的代码看起来像这样:
Dim main as XNameSpace = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
Dim vt as XNameSpace = "http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes"
Dim props as XElement = cXDoc.Element(main + "Properties"
props.Add(New XElement(main + "property"), _
New XAttribute("fmtid", formatId), _
New XAttribute("pid", pid + 1), _
New XAttribute("name", "test"), _
New XElement(vt + "lpwstr", "test value")) _
)添加之前的props中包含的Xml是:
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes" />props.add方法()调用后的Xml是:
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
<property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="test">
<lpwstr xmlns="http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes">test value</lpwstr>
</property>
</Properties>在我应该获取的property元素中
<vt:lpwstr>test value</vt:lpwstr> 但就是不能让这一切发生。这里我也不想要这个元素的xmlns属性。我想我需要以某种方式将vt属性映射回根元素“XNameSpace”中的名称空间声明。有人有什么建议吗?
发布于 2010-02-06 01:34:06
在XElement中的某个位置,您需要定义前缀。下面介绍如何将vt xmlns放在顶部,并将其添加为XAttribute:New XAttribute(XNamespace.Xmlns + "vt", "http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes")
Dim main As XNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
Dim vt As XNamespace = "http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes"
Dim formatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
Dim pid = "2"
Dim props As New XElement(main + "Properties", New XAttribute(XNamespace.Xmlns + "vt", "http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes"))
props.Add(New XElement(main + "property"), _
New XAttribute("fmtid", formatId), _
New XAttribute("pid", pid + 1), _
New XAttribute("name", "test"), _
New XElement(vt + "lpwstr", "test value"))XML文本和全局名称空间可能更容易,但是您仍然需要在父级别的XML中列出vt。下面是一个XML文本示例(请记住将两个Imports语句放在类/模块的顶部,高于其他所有语句):
Imports <xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties">
Imports <xmlns:vt="http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes">
Sub GetXml()
Dim formatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
Dim pid = "2"
Dim props2 = <Properties>
<property fmtid=<%= formatId %> pid=<%= pid + 1 %> name="test">
<vt:lpwstr>test value</vt:lpwstr>
</property>
</Properties>
MsgBox(props2.ToString)
End Sub发布于 2009-11-18 18:53:31
我发现控制名称空间声明位置的方法是使用Xml文字。我还必须从头开始重新创建文档,并将旧文档中的任何现有信息复制到新创建的文档中,这并不理想。在上面的示例中还有一个bug,它足以在运行代码后损坏任何Office文档。
Dim vt as XNameSpace = "http://schemas.openxmlformats.org/officeDocument2006/docPropsVTypes"应该阅读
Dim vt as XNameSpace = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"https://stackoverflow.com/questions/1748003
复制相似问题