I have a variable named "value" that are connected to a remote database and has the value of a xml string. Im wondering how I can take the values from that xml string and display them in my mvc index.cshtml. Do you need to do a model class that repressents the values in the xml string? I need help knowing what to search for, any help will do alot
thx in advance and I hope you understand my concern.
You're question is a little vague but I will try my best to answer it. You can use this to load an XElement from and XML file and then convert that to JSON and then convert to an object.
XElement xml = XElement.Load(path);
var json = JsonConvert.SerializeXNode(xml, Newtonsoft.Json.Formatting.Indented, omitRootObject: true);
Console.WriteLine(json);
File.Delete(path);
var wbexport = JsonConvert.DeserializeObject<WbExport<Column>>(json);
If you are trying to load a string value from a field in a database then you should look at an ORM solution like Dapper or Entity Framework
Dapper:
using(var sql = new SqlConnection(_configuration.GetConnectionString("ConnectionString")))
{
await sql.OpenAsync();
var val = await sql.QueryAsync("<query to get your xml value>");
}
Related
I have seen various questions on this, but none seem to be working in my problem. I have an Umbraco site set up and it stores its page contents as XML in a database column. An example one is below:
Sorry for the screen grab and not the actual code, but the editor kept stripping things out.
What I would like to do ideally is either on the page in c#/Linq (have been trying to manipulate is from a string value) or within a SQL query. To be able to pull out the 'url-name', 'nodeName' and 'bodyText' fields.
Many thanks
Since the column is not defined as XML in the database, you can pull out the string and parse the text/string as an XML document:
// xml would be pulled from the DB
string xml = "<RunwayTextpage nodeName=\"Test page\" urlName=\"test-page\"><bodyText>Body Text</bodyText></RunwayTextpage>";
var doc = XDocument.Parse( xml );
string nodeName = doc.Root.Attribute( "nodeName" ).Value;
string urlName = doc.Root.Attribute( "urlName" ).Value;
string bodyText = doc.Root.Element( "bodyText" ).Value;
Another option would be to use string manipulation in the SQL query itself, but that would end up being much less maintainable whereas the above is easily understandable.
Why don't use uQuery? Don't really know your purposes, but it has a method called GetNodesByXPath that gets a collection of nodes or node from an XPath expression by querying the in memory xml cache.
It's more wise in terms of performance if your tree is large.
I have a silverlight application running on an IIS which currently has some data lists hard coded into the c#, not a good idea I know but this was for a proof of concept demo and now I need to move on to getting the data from another source which can be modified.
I've looked at xml files as well as an sql database. The problem is that the client is reluctant to allow anything extra to be installed on the machine (long security process) and so sql express may not be practical. I've also tried to look into sql compact edition but I cannot seem to be able to find any decent tutorials about it.
The data is made up of three, fairly short, lists of small objects which contain strings and integers. I'm looking for a, preferably, simple and quick to implement solution which ideally does not need anything extra installing on the server.
Does anyone have any suggestions or links which may be handy?
Thanks in advance
Cap
If you are comfortable using LINQ to query your data instead of SQL, Sterling DB sounds perfect for you. It's extremely lightweight, and requires nothing extra on the server or the client (other than including it in your code obviously). It uses isolated storage to store data. All of the serialization/deserialization is taken care of for you by the library.
Edit:
Based on your comment that the data is "static" (meaning all clients consume the same data), it's probably best not to use a client-side database like Sterling or even (as you mentioned) SQL CE. You are right to have reservations about hard-coding this type of "catalog" data, as changes in that data would require a new release of software.
A simple way to make the abstraction is to simply host an XML file alongside your XAP that contains all your data. You can author the XML in any way you want. In the software, it should be fairly straightforward to download the XML file, parse it, and populate your catalog each time the app runs. When changes to the catalog are necessary, it's just a matter of modifying the XML file.
I know this is not an ideal solution but you could try using tab separated text files. They are the easiest to create.
I use XML (web.config) to store data use by all clients such as pre-configure or default user setting value and use Isolated Storage for client-independent data, such as, user UI-layout setting.
I would serialize the objects to XML and store them on the server, it's relatively easy to do
You can pull the values into and XDocument
XDocument ConnectionStrings = XDocument.Load(System.AppDomain.CurrentDomain.BaseDirectory + "ConnectionStrings.xml");
Here are the serialization function i'm using
private static XDocument Serialize<T>(object obj)
{
XDocument ReturnValue = new XDocument();
//Create our Serializer with the type that was passed in
XmlSerializer Serializer = new XmlSerializer(typeof(T));
//Serialize our object to a string writer
System.IO.StringWriter sw = new System.IO.StringWriter();
Serializer.Serialize(sw, obj);
//We use a string reader to read the string from our Writer (created when serialized)
System.IO.StringReader sr;
sr = new System.IO.StringReader(sw.ToString());
//Then we can load the string reader giving us an XDocument
ReturnValue = XDocument.Load(sr);
return ReturnValue;
}
private static T Deserialize<T>(XDocument Xdoc)
{
T ReturnValue;
//Create our Serializer with the type that was passed in
XmlSerializer Serializer = new XmlSerializer(typeof(T));
//Create a string reader to access the XML data in our XDocument
System.IO.StringReader sr = new System.IO.StringReader(Xdoc.ToString());
//Deserialize the XML into our object
ReturnValue = (T)Serializer.Deserialize(sr);
return ReturnValue;
}
I am trying to convert a JSOn string into a Mongo document and there is not much help availabel online.
the only helpful thing that I found was:
1:
2:
MongoDB.Bson.BsonDocument doc4=MongoDB.Bson.Serialization
.BsonSerializer.Deserialize(genericjson);
Toggle HighlightingOpen in New WindowSelect All
as described in the post #
Convert string into MongoDB BsonDocument
It creates the document in the databse but it's not the simulation of what it is here in C#. When I click on the nodes they don't show me the data inside. this is what Mongo does when the conversion has corrupted the file.
is there any other way to solve it?
Try the BsonDocument.Parse() method, e.g.
var bsonDoc = BsonDocument.Parse(jsonString);
I have an app which should read the data from an xml file and then use that data.
How can I import an xml file in my app (what's the code for that) and how can I use the data from that xml file?
Here's an example of the xml database I use:
<Data>
<Animals>
<A>
<word>Ant</word>
<word>Aardwark</word>
</A>
<B>
<word>Bear</word>
<word>Boa</word>
</B>
</Animals>
</Data>
Also I tried this
XDocument loadedData = XDocument.Load("Data.xml");
to read the data from the xml file but didn't work.
Also the in what form can I use the xml data? In other words the xml data would be in a string format or an "X-Something" format?
Update: Maybe Xml Deserialization would work for me?
Thank you in advance
If "Data.xml" is in the root of the project, make sure the Build Action is set to Content and your code should work.
Linq2XML is your friend, and will help you do just that! Mind you that it'll be read-only, unless you place it in the Isolated Storage.
No need for IsoStore if you already have the file and it is the same for every app instance (given that you only need to read it). Simply do what Matt said to quickly get the contents. I would recommend deserializing it to a separate class, so that you can easily reuse and modify the data.
Now, if you want to store the data, you can later easily serialize the existing class and store it locally. In case you want to go a bit deeper into data storage, you could use SQL CE, that is included in Mango and will allow you to manipulate SDF files (which, by the way, can be loaded separately with app instances). Also, a good idea would be to look into Sterling DB (will use IsoStore).
Using the System.XML namespace, use the following code.
XmlDocument xml = new XmlDocument();
xml.LoadXml("your string of xml");
XmlNode xNode = xml.SelectSingleNode("xpath to a single node");
XmlNodeList xNodeList = xml.SelectNodes("xpath to multiple nodes");
You can treat xNode and xNodeList kind of like array results sets and view their contents using the bracket syntax like xNodeList[0].
I want to read a xml file data and extract information from it to show in a form in a C#.Net vs2008 env.
I can't read this data into a list in Memory, but I want to have a .exe file from project that can run in another computer System. So I think, I can't use database for saving and retrieving data!
Please help me to solve my problem!
Use System.Xml.XmlReader to read the XML file. This is a forward only reader which only loads a bit of XML at a time.
Combine this with an iterator method which produces an IEnumerable, such as this example, where MyXmlData is a class representing what is held in the XML file and a class that your forms can work with:
public IEnumerable<MyXmlData> QueryFile(String xmlFile)
{
using (var reader = XmlReader.Create(xmlFile))
{
// These are the variables you want to read for each 'object' in the
// xml file.
var prop1 = String.Empty;
var prop2 = 0;
var prop3 = DateTime.Today;
while (reader.Read())
{
// Here you'll have to read an xml node at a time.
// As you read, assign appropriate values to the variables
// declared above.
if (/* Have we finished reading an item? */)
{
// Once you've completed reading xml representing a single
// MyXmlData object, return it using yield return.
yield return new MyXmlData(prop1, prop2, prop3);
}
}
}
}
The value returned from that method is a sequence of MyXmlData objects where each one will be created on demand as the file is read, one at a time. This will greatly reduce memory requirements for a large XML file.
You can then query your MyXmlData objects using Linq functions. For example, you can emulate paging by using the Take and Skip methods.
// Third page - 50 objects per page.
QueryFile(#"x.xml").Skip(100).Take(50);
Recently microsoft provide a synidcation class in WCF. you can use it for doing this task
You should look into VTD-XML, it is the most efficient xml parser in terms of memory usage without losing random access and xpath..
http://vtd-xml.sf.net