I'm creating a Console App, .Net Core 1.1, and am trying to read an XML file. I brought in the System.Xml.XmlDocument nuGet package, created an XmlDocument, and then attempted to load using the file name. To my surprise, there is no overload for Load(string). See the attached image from the object browser. Is this permanently gone? I tried finding documentation, but was unsuccessful and mainly just found information like here
using System;
using System.Xml;
using System.Xml.Linq;
namespace ReadingXmlDemo
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
string content =
doc.Load("Example.xml");
The XmlDocument.Load(string) method is part of .NET Core 2.0 and .NET Standard 2.0. For .NET Core 1.*, you'll need to use the Load(Stream) method and pass it FileStream obtained via File.Open.
You can check the availability of the method at API .NET Catalog for System.Xml.XmlDocument.Load(String)
see simple exemple:
string sourceFileXML = #"c:\temp\file.xml";
var xml = new XmlDocument();
using (var sr = new StreamReader(sourceFileXML)) {
xml.Load(sr);
}
Related
In ASP .NET Core, I am trying to add some XML-Element with attributes to an existing XML file.
In ASP NET 4.5, I would have used the code below to make this working:
string path = Server.MapPath("~/Data/foo.xml");
XDocument xdoc = XDocument.Load(path);
//Do stuff with XElement and XAttributes...
xdoc.Save(path);
But with ASP .NET Core, I cannot use Server.MapPath(), So I get the complete path with IHostingEnvironment instead: (Read more here )
Running the complete code below on ASP .NET Core will result in "Cannot convert from String to System.IO.Stream" when trying to run "xdoc.Save(pathToDataFile);" ??
var contentRoot = hostingEnvironment.ContentRootPath;
string pathToDataFile = contentRoot + "\\Data\\foo.xml";
XDocument xdoc = XDocument.Load(pathToDataFile);
//Do stuff with XElement and XAttributes...
xdoc.Save(pathToDataFile);
Why is "xdoc.Save()" not working in ASP .NET Core but working fine in .NET 4.5?
APIs available in .NET Core are a subset of the ones available in the full .NET framework. In some areas, you'll find that pretty much everything from .NET 4.5 is available in .NET Core, but that's not always the case.
In your case, if you have a look with Visual Studio at what overloads of the Save method are available, you'll find these ones:
public void Save(Stream stream);
public void Save(TextWriter textWriter);
public void Save(XmlWriter writer);
public void Save(Stream stream, SaveOptions options);
public void Save(TextWriter textWriter, SaveOptions options);
The reason why you have a compilation error is now pretty clear. In .NET Core, there's no overload accepting a string that defines the file path where the document should be saved.
You'll have to create a write-enabled Stream pointing to the desired path first and pass that Stream to the Save method. You can have a look at the full .NET framework implementation for reference.
I had the same issue, and FileStream works for me.
FileStream fileStream = new FileStream("file.xml", FileMode.Create);
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true};
XmlWriter writer = XmlWriter.Create(fileStream, settings);
Remember to use the following lines of code to prevent the file from being truncated.
writer.Flush();
fileStream.Flush();
I am trying to read an XML file into an object in a C# project. Basing it off this article DON’T PARSE THAT XML! and this solution
Then type
xsd myFile.xsd /c
This will generate a set of classes that you can add to your project,
and then you can deserialize an xml file with this simple code:
1: XmlSerializer serializer = 2: new
XmlSerializer(typeof(MyFile)); 3: 4: Stream reader = new
FileStream("myFile.xml",FileMode.Open); 5: 6: MyFile myFile =
(MyFile) serializer.Deserialize(reader); It really is that simple.
There is no excuse for hand writing XML parsing code when you can
literally take an XML file you have never seen before and turn it into
an object in memory in 10 minutes. The serialization framework and XSD
tool provide options for using attributes to control how the XML is
generated also.
So I had already created my XSD and xsd myFile.xsd /c ran succeffuly.
In writing my code to serialize to object I keep getting XmlSerializer does not take a constructor with one argument.
When referring to the MSDN Class docs and the MSDN Examples my code looks like it should work, what is wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization.XmlSerializer;
namespace testxmlc
{
public class XmlSerializer
{
class Program
{
static void Main (string filename)
{
XmlSerializer Serializer = new XmlSerializer(typeof(MyFile));
Stream reader = new FileStream("myFile.xml", FileMode.Open);
MyFile myFile = (MyFile)serializer.Deserialize(reader);
}
}
}
}
You are defining a class XmlSerializer that is conflicting with the .NET class XmlSerializer:
public class XmlSerializer
{
class Program
{
Also your usings are wrong. You need "using System.IO", and "using System.Xml.Serialization", and get rid of "using System.Xml.Serialization.XmlSerializer".
i've got a task to convert docx document to Pdf. I've decided to take this approach:
convert docx to html, then pass html to ItextSharp. Few week i've been looking all over google, codeplex, sourceforge and stackoverflow and so on for a solution thow to make this conversion, until I found Eric White blog. At firs impression he made great tool for working with OpenXml documents. But when I tried to test it I've got an error about null reference. Error occurs when reading header (RevisionAccepter class)
public static void AcceptRevisions(WordprocessingDocument doc)
{
AcceptRevisionsForPart(doc.MainDocumentPart);
foreach (var part in doc.MainDocumentPart.HeaderParts) //part is null
AcceptRevisionsForPart(part); //null ref exception here
foreach (var part in doc.MainDocumentPart.FooterParts)
AcceptRevisionsForPart(part);
if (doc.MainDocumentPart.EndnotesPart != null)
AcceptRevisionsForPart(doc.MainDocumentPart.EndnotesPart);
if (doc.MainDocumentPart.FootnotesPart != null)
AcceptRevisionsForPart(doc.MainDocumentPart.FootnotesPart);
}
code I use for conversion (same as in example)
private void conv()
{
byte[] byteArray = File.ReadAllBytes(textBox1.Text);
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument doc =
WordprocessingDocument.Open(memoryStream, true))
{
HtmlConverterSettings settings = new HtmlConverterSettings()
{
PageTitle = "My Page Title"
};
XElement html = HtmlConverter.ConvertToHtml(doc, settings);
File.WriteAllText("Test.html", html.ToStringNewLineOnAttributes());
}
}
}
nameSpaces:
using System.Xml;
using System.Xml.Xsl;
using OpenXmlPowerTools;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
I tried to pass documents created by word 2010, with header and without and still getting errors in the same place. Maybe I'm passing document incorrectly or something with the document itself.
Maybe there is another way to convert docx to pdf without using comercial components, like Apose.
found the problem. Errors was occuring because of different references between power tools project and main project.
DocumentFormat.OpenXml version on my project was 2.5.5513.0 and on power tools - 2.0.5022.0
After making references to the same resource everything went fine.
I'm trying to embed an XML file into a C# console application via Right clicking on file -> Build Action -> Embedded Resource.
How do I then access this embedded resource?
XDocument XMLDoc = XDocument.Load(???);
Edit: Hi all, despite all the bashing this question received, here's an update.
I managed to get it working by using
XDocument.Load(new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Namespace.FolderName.FileName.Extension")))
It didn't work previously because the folder name containing the resource file within the project was not included (none of the examples I found seemed to have that).
Thanks everyone who tried to help.
Something along these lines
using System.IO;
using System.Reflection;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.XMLFile1.xml");
StreamReader reader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
}
}
}
Here is a link to the Microsoft doc that describes how to do it. http://support.microsoft.com/kb/319292
I'm currently trying to find a PDF library which will run without a running X server. I have already tried the following...
Migradoc/PDFSharp (requires X)
ITextSharp (requires X)
SharpPDF (might work, but I am looking for something with a bit more features)
The library does not have to be opensource or free.
My solution runs on Apache2.2 mod_mono.
Does anyone know of such library?
--- edit ---
The test code used for itextsharp, which produces errors on my testserver is listed below (the code for Migradoc and SharpPDF is just as simple):
using System;
using sharp=iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.IO;
namespace pdftester
{
public static class ITextSharpTest
{
public static void HelloWorld(string filename)
{
Stream stream = new FileStream(filename, FileMode.Create);
sharp.Document document = new sharp.Document();
PdfWriter.GetInstance(document, stream);
document.Open();
document.Add(new sharp.Paragraph("Hello world"));
document.Close();
}
}
}
Since no one has given a definitive answer to the thread, i'm closing it.
I've chosen to go the sharpPDF way, as it's the only one supported on my server. I'll simply have to implement what's needed for my project.
Thanks for the help received so far :)