C# XDocument具有不同本地名称的重复命名空间
我有一个如下所示的XML文档:C# XDocument具有不同本地名称的重复命名空间,c#,xml,linq,entity-framework,linq-to-xml,C#,Xml,Linq,Entity Framework,Linq To Xml,我有一个如下所示的XML文档: <Schema Namespace="BBSF_Model" Alias="Self" p1:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:p1="http://schemas.microsoft.com/ado/2009/02/edm/an
<Schema Namespace="BBSF_Model" Alias="Self"
p1:UseStrongSpatialTypes="false"
xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns:p1="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityType Name="Customer">
<Property Name="Id" Type="Guid" Nullable="false" />
</EntityType>
</Schema>
保存XDocument时,Property元素如下所示:
<Property Name="Id" Type="Guid" Nullable="false" p1:StoreGeneratedPattern="Computed" />
我无法更改或篡改根节点
如何保存文档或更新Property元素以提供所需的输出?从理论上讲,无论是使用前缀
p1:StoreGeneratedPattern=“Computed”
还是注释:StoreGeneratedPattern=“Computed”
,都不重要,因为它们的意思完全相同——元素的值为{http://schemas.microsoft.com/ado/2009/02/edm/annotation}StoreGeneratedPattern
。如果您的接收XML解析器(或QA部门?)在处理此问题时遇到问题,最简单的修复方法可能是将解析器修复为
也就是说,从forXElement
,结果是在写入时按添加顺序将名称空间/前缀属性对推送到,然后检查堆栈中元素名称空间的匹配情况——有效地按添加属性的相反顺序进行匹配前缀注释
,您可以简单地排列根元素中重复名称空间的顺序。(有关详细信息,请参阅。)
但是,您编写了无法更改或篡改根节点的代码。因此,您将被迫做一些工作:您将需要创建自己的XmlWriter
包装子类,并自己重新映射前缀
首先,XmlWriter
的一个非抽象子类,它包装了一个“real”XmlWriter
:
public class XmlWriterProxy : XmlWriter
{
readonly XmlWriter baseWriter;
public XmlWriterProxy(XmlWriter baseWriter)
{
if (baseWriter == null)
throw new ArgumentNullException();
this.baseWriter = baseWriter;
}
protected virtual bool IsSuspended { get { return false; } }
public override void Close()
{
baseWriter.Close();
}
public override void Flush()
{
baseWriter.Flush();
}
public override string LookupPrefix(string ns)
{
return baseWriter.LookupPrefix(ns);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
if (IsSuspended)
return;
baseWriter.WriteBase64(buffer, index, count);
}
public override void WriteCData(string text)
{
if (IsSuspended)
return;
baseWriter.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
if (IsSuspended)
return;
baseWriter.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
if (IsSuspended)
return;
baseWriter.WriteChars(buffer, index, count);
}
public override void WriteComment(string text)
{
if (IsSuspended)
return;
baseWriter.WriteComment(text);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
if (IsSuspended)
return;
baseWriter.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteEndAttribute()
{
if (IsSuspended)
return;
baseWriter.WriteEndAttribute();
}
public override void WriteEndDocument()
{
if (IsSuspended)
return;
baseWriter.WriteEndDocument();
}
public override void WriteEndElement()
{
if (IsSuspended)
return;
baseWriter.WriteEndElement();
}
public override void WriteEntityRef(string name)
{
if (IsSuspended)
return;
baseWriter.WriteEntityRef(name);
}
public override void WriteFullEndElement()
{
if (IsSuspended)
return;
baseWriter.WriteFullEndElement();
}
public override void WriteProcessingInstruction(string name, string text)
{
if (IsSuspended)
return;
baseWriter.WriteProcessingInstruction(name, text);
}
public override void WriteRaw(string data)
{
if (IsSuspended)
return;
baseWriter.WriteRaw(data);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
if (IsSuspended)
return;
baseWriter.WriteRaw(buffer, index, count);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
if (IsSuspended)
return;
baseWriter.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteStartDocument(bool standalone)
{
baseWriter.WriteStartDocument(standalone);
}
public override void WriteStartDocument()
{
baseWriter.WriteStartDocument();
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
if (IsSuspended)
return;
baseWriter.WriteStartElement(prefix, localName, ns);
}
public override WriteState WriteState
{
get { return baseWriter.WriteState; }
}
public override void WriteString(string text)
{
if (IsSuspended)
return;
baseWriter.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (IsSuspended)
return;
baseWriter.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteWhitespace(string ws)
{
if (IsSuspended)
return;
baseWriter.WriteWhitespace(ws);
}
}
接下来,是允许重新映射属性命名空间前缀的子类:
public class PrefixSelectingXmlWriterProxy : XmlWriterProxy
{
readonly Stack<XName> elements = new Stack<XName>();
readonly Func<string, string, string, Stack<XName>, string> attributePrefixMap;
public PrefixSelectingXmlWriterProxy(XmlWriter baseWriter, Func<string, string, string, Stack<XName>, string> attributePrefixMap)
: base(baseWriter)
{
if (attributePrefixMap == null)
throw new NullReferenceException();
this.attributePrefixMap = attributePrefixMap;
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
prefix = attributePrefixMap(prefix, localName, ns, elements);
base.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement(prefix, localName, ns);
elements.Push(XName.Get(localName, ns));
}
public override void WriteEndElement()
{
base.WriteEndElement();
elements.Pop(); // Pop after base.WriteEndElement() lets the base class throw an exception on a stack error.
}
}
公共类前缀选择XmlWriterProxy:XmlWriterProxy
{
只读堆栈元素=新堆栈();
只读函数attributePrefixMap;
公共前缀选择XmlWriterProxy(XmlWriter baseWriter,Func attributePrefixMap)
:base(baseWriter)
{
if(attributePrefixMap==null)
抛出新的NullReferenceException();
this.attributePrefixMap=attributePrefixMap;
}
public override void WriteStartAttribute(字符串前缀、字符串localName、字符串ns)
{
前缀=attributePrefixMap(前缀、localName、ns、元素);
base.WriteStartAttribute(前缀、localName、ns);
}
public override void writeStarteElement(字符串前缀、字符串localName、字符串ns)
{
base.writeStarteElement(前缀、localName、ns);
elements.Push(XName.Get(localName,ns));
}
公共覆盖无效WriteEndElement()
{
base.WriteEndElement();
elements.Pop();//base.WriteEndElement()允许基类在堆栈错误上引发异常。
}
}
最后,您可以像这样使用它:
string xml;
using (var sw = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, IndentChars = " " }))
using (var xmlWriterProxy = new PrefixSelectingXmlWriterProxy(xmlWriter,
(string prefix, string localName, string ns, Stack<XName> parents) =>
{
if (localName == "StoreGeneratedPattern" && ns == annotation && parents.Peek() == XName.Get("Property", "http://schemas.microsoft.com/ado/2009/11/edm"))
return "annotation";
return prefix;
})
)
{
csdlDoc.WriteTo(xmlWriterProxy);
}
xml = sw.ToString();
}
Debug.WriteLine(xml);
stringxml;
使用(var sw=new StringWriter())
{
使用(var xmlWriter=xmlWriter.Create(sw,新的XmlWriterSettings{Indent=true,IndentChars=”“}))
使用(var xmlWriterProxy=新前缀选择xmlWriterProxy(xmlWriter,
(字符串前缀、字符串localName、字符串ns、堆栈父项)=>
{
如果(localName==“StoreGeneratedPattern”&&ns==注释和父项.Peek()==XName.Get(“属性”http://schemas.microsoft.com/ado/2009/11/edm"))
返回“注释”;
返回前缀;
})
)
{
csdlDoc.WriteTo(xmlWriterProxy);
}
xml=sw.ToString();
}
Debug.WriteLine(xml);
正如您所看到的,这只会重新映射属性前缀,但显然可以通过重写将其扩展为重新映射元素前缀
工作。多亏了你的想法,我找到了一个解决方案。 一般的想法是,我将p1的值更改为添加了新属性的任何内容,然后甚至在保存XDocument之前就将p1返回到其原始值
XAttribute p1 = csdlDoc.Root.Attributes()
.First(a => a.IsNamespaceDeclaration && a.Name.LocalName == "p1");
p1.Value = "http://schemas.microsoft.com/ado/2009/02/edm/annotation/TEMP";
......
// the same update now works as there is only one xmlns
XNamespace annotation = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";
var attrib = new XAttribute(annotation + "StoreGeneratedPattern", "Computed");
csdlProperty.Add(attrib);
p1.Value = "http://schemas.microsoft.com/ado/2009/02/edm/annotation/";
另一个有效的解决方案是在根节点(在注释之前声明p1)交换顺序或声明,如下所示:
<Schema Namespace="BBSF_Model" Alias="Self"
p1:UseStrongSpatialTypes="false"
xmlns:p1="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
一般来说,这两种解决方案看起来都很便宜。您需要从document.XElement schema=doc.Elements().Where(x=>x.Name.LocalName==“schema”).FirstOrDefault();XNamespace annotation=schema.GetNamespaceOfPrefix(“annotation”);@jdweng仍然会得到相同的名称空间,因此会得到相同的结果。这是因为LINQ to XML在内部是如何工作的。如果您交换
注释
和p1
的声明顺序,那么它将做您期望的事情。但是,两者在语义上是相同的。可以说,您应该删除 string xml;
using (var sw = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, IndentChars = " " }))
using (var xmlWriterProxy = new PrefixSelectingXmlWriterProxy(xmlWriter,
(string prefix, string localName, string ns, Stack<XName> parents) =>
{
if (localName == "StoreGeneratedPattern" && ns == annotation && parents.Peek() == XName.Get("Property", "http://schemas.microsoft.com/ado/2009/11/edm"))
return "annotation";
return prefix;
})
)
{
csdlDoc.WriteTo(xmlWriterProxy);
}
xml = sw.ToString();
}
Debug.WriteLine(xml);
XAttribute p1 = csdlDoc.Root.Attributes()
.First(a => a.IsNamespaceDeclaration && a.Name.LocalName == "p1");
p1.Value = "http://schemas.microsoft.com/ado/2009/02/edm/annotation/TEMP";
......
// the same update now works as there is only one xmlns
XNamespace annotation = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";
var attrib = new XAttribute(annotation + "StoreGeneratedPattern", "Computed");
csdlProperty.Add(attrib);
p1.Value = "http://schemas.microsoft.com/ado/2009/02/edm/annotation/";
<Schema Namespace="BBSF_Model" Alias="Self"
p1:UseStrongSpatialTypes="false"
xmlns:p1="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns="http://schemas.microsoft.com/ado/2009/11/edm">