I want to read an specific xml node and its value for example
<customers>
<name>John</name>
<lastname>fetcher</lastname>
</customer>
and my code behind should be some thing like this (I don't know how it should be though):
Response.Write(xml.Node["name"].Value)
As I said it is just an example because I don't know how to do it.
The most basic answer:
Assuming "xml" is an XMLDocument, XMLNodeList, XMLNode, etc...
Response.Write(xml.SelectSingleNode("//name").innerText)
Which version of .NET are you using? If you're using .NET 3.5 and can use LINQ to XML, it's as simple as:
document.Descendant("name").Value
(except with some error handling!) If you're stuk with the DOM API, you might want:
document.SelectSingleNode("//name").InnerText
Note that this hasn't shown anything about how you'd read the XML in the first place - if you need help with that bit, please give more detail in the question.
If using earlier versions of the .Net framework, take a look at the XMLDocument class first as this is what you'd load the XML string into. Subclasses like XMLElement and XMLNode are also useful for doing some of this work.
haven't tried testing it but should point you in the right direction anyway
'Create the XML Document
Dim l_xmld As XmlDocument
'Create the XML Node
Dim l_node As XmlNode
l_xmld = New XmlDocument
'Load the Xml file
l_xmld.LoadXml("XML Filename as String")
'get the attributes
l_node = l_xmld.SelectSingleNode("/customers/name")
Response.Write(l_node.InnerText)
Related
I want to load XML in a single table of a dataset. I use following code
string val = getAbonentInfoParametr(ai,"abonentDescription");
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(val));
but when I do this, I got three tables because in one node of XML file I now get HTML code that I want to have like a string field in my only table. What should I do?
Also I prefer not to use scheme files because the structure of that xml file can be changeable except several field that I use, please suggest me something.
Use CDATA to wrap around the HTML, otherwise there is no way to differentiate HTML from XML.
I have a System.Web.UI.WebControls.Xml control (Xml1) in a webforms app that I have upgraded from .NET 2.0 to .NET 4.0
I am getting two warnings from the code-behind page that I'd like to do something about.
...
Dim ds As DataSet = app.GetObjects
Dim xmlDoc As New System.Xml.XmlDataDocument(ds)
Xml1.Document = xmlDoc
Xml1.TransformSource = "~/xslt/admin_objectslist.xslt"
...
From the second line I get the warning:
'System.Xml.XmlDataDocument' is obsolete: 'XmlDataDocument class will be removed in a future release.'.
And from the third line I get the warning:
'Public Property Document As System.Xml.XmlDocument' is obsolete: 'The recommended alternative is the XPathNavigator property. Create a System.Xml.XPath.XPathDocument and call CreateNavigator() to create an XPathNavigator.
What is the recommended .NET 4.0 replacement for this?
ds.I ran into this problem with 3.5 as well. Here is what I came up with:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(ds.GetXml());
xml1.XPathNavigator = xmlDoc.CreateNavigator();
xml1.TransformSource = #"~/XSLT/LogEntryTransform.xslt";
Hope it helps.
Use Linq2XML - it's way more powerful than any of the other XML tools.... allows you to query and create/read/update/delete (CRUD) the XML just like you would a dataset or other strongly typed data source.
Once you get started with Linq you'll never go back to the old ways... it absolutely rocks!
I want to add an attribute to the dataset declared below whose value is the value of one of the field in the row.
So I want to add the id as shown below.
<root>
<Table id="GAS-405">
<apple>2009FA</apple>
<orange>3.00</orange>
<pear>BGPR</pear>
<banana>GAS-405</banana>
</Table>
</root>
This will help me identify the node later in my application.
Is this possible? Is this easier to do using XMLDocument?
Dim sdaFoo As SqlDataAdapter = New SqlDataAdapter("SELECT BLAH FROM BLAHBLAH", conn)
Dim dsFoo As DataSet = New DataSet()
dsFoo.DataSetName = "apple"
sdaFoo.Fill(dsFoo)
dsFoo.WriteXml("C:\Inetpub\wwwroot\foo.xml")
Dataset.WriteXml() is really a convenience method rather than a flexible way of dealing with XML.
You'll need to take another approach. There are a few options:
If you're just adding a single attribute, you could hack it into the resulting xml by re-opening the file as an XDocument, adding the attribute to the necessary element, and saving it again. Not too elegant, but easy, and sometimes easy is best. Even better, just use WriteXml() to put your xml into a string, then load the string as your XDocument.
Generate the XML from your query directly, rather than as a dataset. Sql Server 2005 and 2008 have some good XML methods that allow you to select a set of rows as XML (SELECT ... FOR XML) and specify what it looks like.
Use XmlSerialization for your dataset and inject the attribute using custom control of the serialization process.... which will be way more trouble than it's worth.
Store the attribute somewhere else outside of your XML and use some kind of object to keep track of it. Not really sure what your code is like, but that might be a great option.
Use GetXML() method of DataSet to get whole XML as a string. Then add your custom attributes and write that string into xml file using StreamWriter.
I would like to upload a Word 2007 or greater docx file to my web server and convert the table of contents to a simple xml structure. Doing this on the desktop with traditional VBA seems like it would have been easy. Looking at the WordprocessingML XML data used to create the docx file is confusing. Is there a way (without COM) to navigate the document in more of an object-oriented fashion?
I highly recommend looking into the Open XML SDK 2.0. It's a CTP, but I've found it extremely useful in manipulating xmlx files without having to deal with COM at all. The documentation is a bit sketchy, but the key thing to look for is the DocumentFormat.OpenXml.Packaging.WordprocessingDocument class. You can pick apart the .docx document if you rename the extension to .zip and dig into the XML files there. From doing that, it looks like a Table of Contents is contained in a "Structured Document" tag and that things like the headings are in a hyperlink from there. Putzing around with it a bit, I found that something like this should work (or at least give you a starting point).
WordprocessingDocument wordDoc = WordprocessingDocument.Open(Filename, false);
SdtBlock contents = wordDoc.MainDocumentPart.Document.Descendants<SdtBlock>().First();
List<string> contentList = new List<string>();
foreach (Hyperlink section in contents.Descendants<Hyperlink>())
{
contentList.Add(section.Descendants<Text>().First().Text);
}
Here is a blog post on querying Open XML WordprocessingML documents using LINQ to XML. Using that code, you can write a query as follows:
using (WordprocessingDocument doc =
WordprocessingDocument.Open(filename, false))
{
foreach (var p in doc.MainDocumentPart.Paragraphs())
{
Console.WriteLine("Style: {0} Text: >{1}<",
p.StyleName.PadRight(16), p.Text);
foreach (var c in p.Comments())
Console.WriteLine(
" Comment Author:{0} Text:>{1}<",
c.Author, c.Text);
}
}
Blog post: Open XML SDK and LINQ to XML
-Eric
See XML Documents and Data as a starting point. In particular, you'll want to use LINQ to XML.
In general, you do not want to use COM in a .NET application.
I need to create a service that will return XML containing data from the database. So I am thinking about using an ASHX that will accept things like date range and POST an XML file back. I have dealt with pages pulling data from SQL Server and populating into a datagrid for visual display but never into XML for delivery, what is the best way to do this? Also if an ASHX and POST isn't the best method for delivery let me know... thanks!
EDIT: These answers are great and pointing me in the right direction. I should have also mentioned that the XML format has already been decided so I can't use any automatically generated one.
Combining linq2sqlwith the XElement classes, something along the lines:
var xmlContacts =
new XElement("contacts",
(from c in context.Contacts
select new XElement("contact",
new XElement
{
new XElement("name", c.Name),
new XElement("phone", c.Phone),
new XElement("postal", c.Postal)
)
)
).ToArray()
)
);
Linq2sql will retrieve the data in a single call to the db, and the processing of the XML will be done at the business server. This splits the load better, since you don't have the sql server doing all the job.
Have you tried DataSet.WriteXml()?
You could have this be the output of a web service call.
Sql Server 2005 and above has a "FOR XML AUTO" command that will convert your recordset to XML for you. Then you just have to return a string from your ASHX.
Beginning with SQL Server 2000, you can return query results as XML. For absolute control of them, use the "FOR XML EXPLICIT" command. You can use any format you desire that way.
http://msdn.microsoft.com/en-us/library/ms189068.aspx
It's as easy as writing your result to the raw output then. For added points, you can return the result set to a XPathDocument, pass it through an XSL transformation, and send the results out in any format you choose (HTML vs XML at the click of a button perhaps).
you can obtained that to a datatable and then call myTable.WriteXML()
if you are populating classes with the your database results then add the serializable attribute to the header your classes, and use the XMLSerializer
Converting an automatically generated format into a specified one is a job for xslt. Just find a way to run the output from the tool through an xslt filter.
Oracle has a great product for doing exactly this job - the oracle XDK. But it's a java thing, not ASP as far as I know.
For an example, this XHTML
http://www.anbg.gov.au/abrs/online-resources/flora/stddisplay.xsql?pnid=2524
is generated automatically from this XML, which is generated by oracle
http://www.anbg.gov.au/abrs/online-resources/flora/stddisplay.xsql?pnid=2524&xml-stylesheet=none
Of course, you are not after XHTML, but some other XML format. But XSLT will do the job.