c# - how to add namespace using XmlWriter in xml document -
hi have save file in xfdf file in c# using xmlwriter class;
using (var fs = file.open("d://abc.xfdf", filemode.create)) { try { var doc = xmlwriter.create(fs); doc.writestartelement("highlights"); foreach (var h in highlights) { doc.writestartelement("highlight"); doc.writeelementstring("id", h.id); doc.writeendelement(); } doc.writeendelement(); doc.flush(); } }
but not able save in xfdf file. getting problem adding
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
your link doesn't explain problem is, i'll take sample bit of xml there , walk through creating it. principles can applied whichever elements you're trying create.
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve"> <f href="document.pdf"/> <fields> <field name="street"> <value>345 park ave.</value> </field> </fields> </xfdf>
so, while can xmlwriter
directly, not idea - it's low level , result not nice read or write. example, code take create outer element , first child. notice how have careful match writing start , end of elements:
writer.writestartelement("xfdf", "http://ns.adobe.com/xfdf/"); writer.writeattributestring("space", "http://www.w3.org/xml/1998/namespace", "preserve"); writer.writestartelement("f", "http://ns.adobe.com/xfdf/"); writer.writeattributestring("href", "document.pdf"); writer.writeendelement(); writer.writeendelement();
alternatively, can use higher level, cleaner linq xml api declaratively create xml:
xnamespace ns = "http://ns.adobe.com/xfdf/"; var doc = new xdocument( new xelement(ns + "xfdf", new xattribute(xnamespace.xml + "space", "preserve"), new xelement(ns + "f", new xattribute("href", "document.pdf") ), new xelement(ns + "fields", new xelement(ns + "field", new xattribute("name", "street"), new xelement(ns + "value", "345 park ave." ) ) ) ) ); doc.save(@"d:\abc.xdfd");
you can use api add elements sequence in variety of different ways, such as:
var element = new xelement(ns + "highlights"); foreach (var h in highlights) { element.add(new xelement(ns + "highlight", h.id)); }
or:
var element = new xelement(ns + "highlights", highlights.select(h => new xelement(ns + "highlight", h.id)) );
as ever, google friend. there lots of examples on how use linq xml.
Comments
Post a Comment