XML : How to load and add elements in an XML tree

I have spent the last few days reading here on Stack Overflow, blogs, and MSDN articles. I am clearly lacking some basic understanding of how namespaces, Linq, and XML work and am in need of help. If I had more hair to pull out, it would be in my hand right now :-)

Using C# and Linq to XML, I open the following opf.xml file:

  <?xml version="1.0" encoding="UTF-8"?>  <package version="2.0" xmlns="http://www.idpf.org/2007/opf" unique-identifier="">    <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">    </metadata>    <manifest></manifest>    <spine toc="ncx"></spine>    <guide></guide>  </package>    

I open this file with the following code:

  File.Copy(_opfFile, opfFile, true);  XDocument opfDoc = XDocument.Load(opfFile);    

Here is where I get completely lost, unfortunately. What I need to do is generate elements under each of the major nodes. For the metadata node, I need to create elements with namespaces and non-namespaces. For the remainder of the file, I just need to add regular nodes that do not make use of namespaces.

Below is a sampling of the output I want to achieve. I am sure if you can help me with the metdata and manifest nodes, I can figure out how to update the rest of the nodes.

  <?xml version="1.0" encoding="UTF-8"?>  <package xmlns:ibooks="http://www.idpf.org/2007/opf" unique-identifier="BookId" version="3.0" prefix="ibooks: http://www.idpf.org/2007/opf" xmlns="http://www.idpf.org/2007/opf">      <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">          <dc:title>Untitled</dc:title>          <meta refines="#contributor" property="role" scheme="marc:relators">bkp</meta>      </metadata>      <manifest>          <item id="toc" href="toc.xhtml" media-type="application/xhtml+xml" properties="nav"/>      </manifest>      <spine toc="ncx"></spine>      <guide></guide>  </package>    

Could you please provide some basic C#/Linq code to:

  1. Find and add metadata items requiring the namesapce (ns) of "dc" as in the example above.
  2. Add a metadata item that does not use a namespace as in the example above.
  3. Add a new manifest item as in the example above.

I would share the code I have written but it is all over the place and I have lots of commented code. What I can tell you is I constantly end up null exception errors.

Thank you in advance.

No comments:

Post a Comment