Saturday, June 12, 2010

Reading Header part in Vsto

Code Snippet..


public void XMLRead()
{
try
{
const string mydoc = @"E:\s\WordDocument2.docx";

string xmlstring = "";

using (WordprocessingDocument wdDoc =
WordprocessingDocument.Open(mydoc, false))
{
foreach (HeaderPart hp in wdDoc.MainDocumentPart.HeaderParts)
{
XElement ele = XElement.Load(
XmlReader.Create(hp.GetStream())
);
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
// Console.WriteLine(ele.Descendants(w + "tbl").Count().ToString());
// Console.WriteLine(ele.ToString());
xmlstring = ele.ToString();

}
}

// Console.WriteLine(xmlstring);

StringBuilder output = new StringBuilder();




String xmlString = xmlstring;


string Id = "";
string txtpathvaslue = "";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("v:shape");
// reader.MoveToFirstAttribute();
Id = reader.GetAttribute("id");
output.AppendLine("The genre value: " + Id);


reader.ReadToFollowing("v:textpath");
txtpathvaslue = reader.GetAttribute("string");
output.AppendLine("Content of the title element: " + txtpathvaslue);
}

Console.WriteLine("Id " + Id + " = TxtPath " + txtpathvaslue);



/**********Same thing using Linq to Xml***************/

TextReader tr = new StringReader(xmlString);

TextReader tr2 = new StringReader(xmlString);

XDocument doc = XDocument.Load((new XmlTextReader(tr)));
var query = doc.Element("whdr")
.Element("wp")
.Element("wr")
.Element("wpict")
.Element("vshape")
.Attributes("id");

foreach (XAttribute result in query)
Console.WriteLine(result.Name + " = " + result.Value);



XDocument doc1 = XDocument.Load((new XmlTextReader(tr2)));
var query1 = doc1.Element("whdr")
.Element("wp")
.Element("wr")
.Element("wpict")
.Element("vshape")
.Element("vtextpath")
.Attributes("string");

foreach (XAttribute result1 in query1)
Console.WriteLine(result1.Name + " = " + result1.Value);



/***************************************************/


}
catch (Exception e1)
{
Console.Write(e1.Message);
}

Console.Read();

}

No comments:

Post a Comment