I save all attachments from an email:
List<Pop3Content> contentList = Pop3Message.GetAttachedContents(client.GetMessage(i).Contents, c => c.IsAttachment == true);
XmlDocument xml=new XmlDocument();
xml.LoadXml(contentList[0].BodyText);
this
contentList[0].BodyText
Returns the whole Content of an attached XML file, the way I want to have it in my XmlDocument XML
But the method LoadXML expects a path to an actual XML file. How can I write strings into an "internal" XML file?
This method accepts string.
You can do
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
Read this
I think you need to do this
xml.LoadXml(contentList[0].BodyText.ToString());
Related
I'm trying to read a node in a serialized XML file. Here is the the first part of the XML file (I'm using a screen cap because pasting ended up with weird formatting):
And this is the code I'm using to read the XML and the error it's throwing:
I'm trying to read the <ScenarioDescription> node.
As per request, here's the entire XML file. Unfortunately it's just a complete mess. Here is a link to the XML file.
You should You would need to specify the namespace. In this particular case, the default namespace is used to declare the http://schemas.datacontract.org/2004/07/ModelLib namespace.
var xml = new XmlDocument();
xml.LoadXml(str);
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("x", xml.DocumentElement.NamespaceURI);
var root = xml.DocumentElement;
var test = root.SelectSingleNode("//x:ScenarioDescription",ns);
var scenarioText = test.InnerText;
You can use the following code to access the ScenarioDescription node and its InnerText
var document = new XmlDocument();
document.Load(s);
var root = document.DocumentElement;
var node = root["ScenarioDescription"];
var text = node?.InnerText;
SelectSingleNode accepts the xpath expression, you simply can use XmlElement indexer instead. Otherwise you'll need to create a XmlNamespaceManager instance and add your root namespace to it
You can supply the XmlNamespaceManager object as a parameter to the
SelectNodes or SelectSingleNode method of the XmlDocument class to
execute XPath query expressions that reference namespace-qualified
element and attribute name
I neen apply simple xsl transform and continue work whith result data, but I wan't to save file. This is my code:
XslTransform xsl = new XslTransform();
var writer = new MemoryStream();
var xslDoc = new XPathDocument("107901.xslt");
xsl.Load(#"C:\Users\mak\Documents\Visual Studio 2015\Projects\SpellCheck\SpellCheck\GetAllValues.xslt");
xsl.Transform(xslDoc, null, writer);
writer.Position = 1;
var str = new StreamReader(writer);
var normalize = str.ReadToEnd().Trim('�');
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Save(normalize);
1) Why in variable str appears 2 symbol 65533?
2) Why variable normalize not save how xml file? Goes error 'not able to add it to the content characters than whitespace'
Maybe I doing all wrong and can easier.
Sorry for bad english and sanks for answer :-)
Don't understand question no.1 so I'll skip to question 2. If you care to read the documentation, it is clearly mentioned that the string argument of Save() should contains "The location of the file where you want to save the document". As for populating the XmlDocument instance from XML string, you can use LoadXml() :
.....
.....
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(normalize);
xmlDocument.Save("D:\path\to\your\output.xml");
I basically want to know how to insert a XmlDocument inside another XmlDocument.
The first XmlDocument will have the basic header and footer tags.
The second XmlDocument will be the body/data tag which must be inserted into the first XmlDocument.
string tableData = null;
using(StringWriter sw = new StringWriter())
{
rightsTable.WriteXml(sw);
tableData = sw.ToString();
}
XmlDocument xmlTable = new XmlDocument();
xmlTable.LoadXml(tableData);
StringBuilder build = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(build, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
writer.WriteStartElement("dataheader");
//need to insert the xmlTable here somehow
writer.WriteEndElement();
}
Is there an easier solution to this?
Use importNode feature in your document parser.
You can use this code based on CreateCDataSection method
// Create an XmlCDataSection from your document
var cdata = xmlTable.CreateCDataSection("<test></test>");
XmlElement root = xmlTable.DocumentElement;
// Append the cdata section to your node
root.AppendChild(cdata);
Link : http://msdn.microsoft.com/fr-fr/library/system.xml.xmldocument.createcdatasection.aspx
I am not sure what you are really looking for but this can show how to merge two xml documents (using Linq2xml)
string xml1 =
#"<xml1>
<header>header1</header>
<footer>footer</footer>
</xml1>";
string xml2 =
#"<xml2>
<body>body</body>
<data>footer</data>
</xml2>";
var xdoc1 = XElement.Parse(xml1);
var xdoc2 = XElement.Parse(xml2);
xdoc1.Descendants().First(d => d.Name == "header").AddAfterSelf(xdoc2.Elements());
var newxml = xdoc1.ToString();
OUTPUT
<xml1>
<header>header1</header>
<body>body</body>
<data>footer</data>
<footer>footer</footer>
</xml1>
You will need to write the inner XML files in CDATA sections.
Use writer.WriteCData for such nodes, passing in the inner XML as text.
writer.WriteCData(xmlTable.OuterXml);
Another option (thanks DJQuimby) is to encode the XML to some XML compatible format (say base64) - note that the encoding used must be XML compatible and that some encoding schemes will increase the size of the encoded document (base64 adds ~30%).
string json = "{"Animal":{"id":"123","verified":true}}"
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
returnXml = doc.ToString();
Why does "ReturnXml" return the following text "System.Xml.XmlDocument" and not the XML output in string format?
http://json.codeplex.com/
To print XML, you need to use InnerXml
doc.InnerXml;
The ToString method of XmlDocument is not set to output a pretty version of the xml contained therein.
You're best bet may be to just convert that XmlDocument to an XDocument, since that supports a ToString method that outputs actual XML:
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
XDocument linqXML = XDocument.Load(new XmlNodeReader(doc));
returnXML = linqXML.ToString();
I have a StringBuilder with the contents of an XML file. Inside the XML file is a root tag called <root> and contains multiple <node> tags.
I'd like to parse through the XML to read values of tags within in s, but not sure how to do it.
Will I have to use some C# XML data type for this?
Thanks in advance
StringBuilder sb = new StringBuilder (xml);
TextReader textReader = new StringReader (sb.ToString ());
XDocument xmlDocument = XDocument.Load (textReader);
var nodeValueList = from node in xmlDocument.Descendants ("node")
select node.Value;
You should use classes available in either System.Xml or System.Xml.Linq to parse XML.
XDocument is part of the LINQ extensions for XML and is particularly easy to use if you need to parse through an arbitrary structure. I would suggest using it rather than XmlDocument (unless you have legacy code or are not on .NET 3.5).
Creating an XDocument from a StringBuilder is straightforward:
var doc = XDocument.Parse( stringBuilder.ToString() );
From here, you can use FirstNode, Descendents(), and the many other properties and methods available to walk and examine the XML structure. And since XDocument is designed to work well with LINQ, you can also write queries like:
var someData = from node in doc.Descendants ("yourNodeType")
select node.Value; // etc..
If you are just looking the specifically named nodes then you don't need to load the document into memory, you can process it yourself with an XmlReader.
using(var sr = new StringReader(stringBuilder.ToString)) {
using(var xr = XmlReader.Create(sr)) {
while(xr.Read()) {
if(xr.IsStartElement() && xr.LocalName == "node")
xr.ReadElementString(); //Do something here
}
}
}
use XDocument.Parse(...)
There are several objects at your disposal for working with XML. Look at the System.Xml namespace for objects such as XmlDocument as well as the XmlReader and XmlWriter families of objects. If using C# 3.0+, look at the System.Xml.Linq namespace and the XDocument class.
If you're looking to read all the values in the XML file , you could look into deserializing the XML into a C# data Object.
Deserializing XML into class obj in C#
Yes, I suggest you use an XmlDocument object to parse the content of your string.
Here is an example who print all inner text contained in your tags:
var doc=new XmlDocument();
doc.LoadXml(stringBuilder.TosTring());
XmlNodeList elemList = doc.GetElementsByTagName("node");
for (int i=0; i < elemList.Count; i++)
{
XmlNode node=elemList[i];
Console.WriteLine(node.InnerText);
}
using Node object members, you can also easily extract all you attributes .