开发者

Write a XDocument out with annotations

I have a XDocument where I have added some annotations (.AddAnnotation). Now I开发者_运维技巧 want to write the document out with these annotations. Both .ToString and .WriteTo will discard annotations so they will not work. Essentially, I need a custom XML writer but the abstract class XmlWriter don't have any notion about annotations on elements and attributes. The specific problem is that I have to write some stuff before an element with a specific annotation and the same thing with attributes.

A solution where I don't have to write every single bit (which the XMLWriter do) but only handles the two cases I need (before elements with a annotation and before attributes with a annotation) will be appreciated.

A partially solution I have is to either wrap the elements with this specific annotation in another element but this mess up the XML and do not work on attributes. Another solution is to replace the annotations with XComment´s instead before elements for both elements and attributes. But then I would have to replace the comments afterwards. I might go with the last solution but there could be comments already which potentially could have the same format I'm applying the comments.

Example:

var annoAtt = new XAttribute("Name", "Foo");
annoAtt.AddAnnotation(new Foo());

var doc = new XDocument(
            new XElement("Root",
                new XElement("Some",
                    annoAtt))));

I then wants this as the output (not valid XML but I don't need that):

<Root>
   <Some {Something}Name="Foo"/>
</Root>

I could make something like:

<Root>
   <Some my:Something="Name ..." Name="Foo"/>
</Root>

but that is really not what I want.

If I could get the start position of elements and attributes it would be perfect. I'm trying to implement that with:

http://blogs.msdn.com/b/mikechampion/archive/2006/09/10/748408.aspx


Given that annotations are arbitrary objects, it's not surprising that they're not written out. They're not really part of the XML document model - they're just additions for LINQ to XML. What do you need to persist in the annotations? If it's just string data, you might want to create an attribute instead (perhaps in your own namespace, so it's easy to avoid conflicts). Admittedly that could be tricky if you want to add annotations to text nodes, but you could reasonably easily add them to both elements and attributes. (Have two different kinds of attribute, one of which specifies which attribute it applies to as part of its data.)

Basically if you want data persisted within the XML representation, it will need to be part of the normal XML document model.


Problem solved :-)

With XDocument.Load(reader, LoadOptions.SetLineInfo) I can get line number and position on the line with:

var info = (IXmlLineInfo)element;

And the stuff I need can be injected with these informations

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜