Filepath to xml within xlsx in c#
I'm doing an xslt transform of the xml within an excel file using Saxon where the transform is being done on the .rels xml file within the xlsx file. I currently have a workaround in place where I have unzipped the entire contents of the xlsx file into a seperate folder. However, for simplicity's sake my program takes the xlsx file as it's input, so I was wondering if there was a simpler way for my program to point to the xml within the xlsx file without the need to unzip the contents. I've tried pathing to file.xlsx\_rels\.rels but that doesn't seem to work. The code I'm current using for this input is
String inputFile = "file.xls开发者_如何学Pythonx_folder\\_rels\\.rels"
XdmNode input = processor.NewDocumentBuilder().Build(new Uri(inputFile));
but I would like to have that point directly within the xlsx.
Yes there is a simpler way, you don't need to unzip the whole file.
Instead of the file path you've passed as a parameter to the Saxon APIs Build function, pass an XmlReader or Stream instance of the uncompressed part of the xslx file.
The Open static method of System.IO.Packaging.Package can be used to get a Package instance on which you call GetStream to uncompress the part you need and return it as a Stream. Package handles files conforming to the Open Packaging Convention, like Excel's xslx format.
The code below uncompresses the package part to a Stream, uses this to create an XmlReader instance, and finally passes the XmlReader as the parameter to the Build function:
string filename = "c:\\test\\file.xslx";
string partPath = "/_rels/.rels";
Package xpsPackage = Package.Open(fileName, FileMode.Open)
Uri partUri = new Uri(partPath, UriKind.Relative);
PackagePart xpsPart = xpsPackage.GetPart(partUri);
Stream xpsStream = xpsPart.GetStream(FileMode.Open)
XmlReader xmlReader = XmlReader.Create(xpsStream);
XdmNode input = processor.NewDocumentBuilder().Build(xmlReader);
精彩评论