namespace not loading correctly - c#

I am reading in an xml namespace through a local file. When I am outputting I am getting
"
in the namespace. What am I doing wrong?
sample namespace looks like
xmlns="urn:rosettanet:specification:interchange:ShipmentReceiptNotification:xsd:schema:02.02"
xmlns:dacc="urn:rosettanet:specification:domain:Procurement:AccountClassification:xsd:codelist:01.03"
I am loading the namespace as follows:
string contents = File.ReadAllText("loadNamespaces.txt");
XmlNode ShipmentReceiptNotification0Node = xmlDoc.CreateElement("ShipmentReceiptNotification", contents);

In the CreateElement method, the second parameter is only the namespace. Just the "urn:rosettanet:specification:interchange:ShipmentReceiptNotification:xsd:schema:02.02" part.

Related

There is an error in XML document when deserializing(C#)

I have the following xml:
XML
I have the following C# class
C# GlobalClass
I am trying to convert the xml content into C# custom object like that:
string xmlFilePath = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Settings4/settings.xml";
XmlSerializer deserializer = new XmlSerializer(typeof(GlobalClass));
TextReader textReader = new StreamReader(xmlFilePath);
GlobalClass globalVariables;
globalVariables = (GlobalClass)deserializer.Deserialize(textReader);
textReader.Close();
But I get
There is an error in XML document
on the line of code
globalVariables = (GlobalClass)deserializer.Deserialize(textReader);
I make GlobalClass inherit from Application because I want GlobalClass to be global that is to say I want to use its properties throughout all activities. What I'm doing wrong to recieve that error?
In your class put something like this [Serializable, XmlRoot("YourRoot")]
When you work with deserialization it might not found.
From MSDN
The name of the XML root element that is generated and recognized in
an XML-document instance. The default is the name of the serialized
class.

How to use the special "xml" namespace prefix with XElement

I'm using XElement to build an XML document in C# and I'm trying to set
<myEelment xml:space="preserve">
Here's my current attempt:
myElement.SetAttributeValue(XName.Get("space", "xml"), "preserve");
but it comes out like this:
<myEelment p4:space="preserve" xmlns:p4="xml">
I understand how this is going wrong - my code is using "xml" as a namespace URI when I want to use as a namespace prefix. My problem is that AFAICT the "xml" namespace prefix is somehow implicit and doesn't actually have a namespace URI associated with it. So how can I generate attributes with the namespace prefix "xml"?
Standard namespaces are available as properties on the XNamespace class. Use that.
var myElement = doc.Descendants("myElement").Single();
myElement.SetAttributeValue(XNamespace.Xml + "space", "preserve");

Databinding XML in C# (WP8)

I'm not sure if this is correct, but trying to learn MVVM, how it works, etc.
Currently, the example used to load the data is:
this.SavedItems.Add(new SavedBoard() { ID= "1098", UserDescription = "Test" });
I want to parse XML and load data from there.
This is the c# code I've been trying but doesn't seem to work:
XDocument doc = XDocument.Load("savedstops.xml");
var data = from query in doc.Descendants("Stops")
select new SavedBoard
{
ID = query.Element("ID").Value,
UserDescription = query.Element("UserDescription").Value
};
this.SavedItems.Add(data);
And this is the XML file:
<Stops>
<Stop>
<ID>1022</ID>
<UserDescription>Test</UserDescription>
</Stop>
<Stop>
<ID>1053</ID>
<UserDescription>Test1045</UserDescription>
</Stop>
</Stops>
Where am I going wrong? I also get an error Error "Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable'. 'Select' not found. Are you missing a reference or a using directive for 'System.Linq'?"
Though I'm thinking the error isn't the reason it's not working, but rather the code logic itself.
Thanks in advance!
Use doc.Descendants("Stop") (or doc.Root.Elements("Stop")) instead of Stops, and include the System.Linq namespace with adding: using System.Linq; top of your code.

How to write simple query to XElement?

Trying to use Linq to XML for the first time and having some problems. I have this XML file that needs to be read and used for various tasks. The file contains a list of entities called 'interfaces'. To start with I want to display a list of names of these interfaces.
Here is the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<InterfaceList>
<Interface>
<InterfaceName>Account Lookup</InterfaceName>
<RequestXSD>ALREQ.xsd</RequestXSD>
<ResponseXSD>ALRES.xsd</ResponseXSD>
</Interface>
<Interface>
<InterfaceName>Balance Inquiry</InterfaceName>
<RequestXSD>BIREQ.xsd</RequestXSD>
<ResponseXSD>BIRES.xsd</ResponseXSD>
</Interface>
</InterfaceList>
Here is the query code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Stub {
public class InterfaceList : XElement {
public void GetInterfaceNameList() {
var v = from interface in this.Elements("Interface")
select interface.Element("InterfaceName").Value;
}
}
}
The idea is to load InterfaceList from the file, and then to use it to query any I may need.
The problem is that I'm getting error message for everything in the query. here are a few of them:
Error 14 The name 'from' does not exist in the current context
Error 15 The type or namespace name 'select' could not be found (are
you missing a using directive or an assembly reference?)
Error
Error 16 'System.Xml.Linq.XElement.Value' is a 'property' but is used
like a 'type'
What's wrong here?
If you want to call your variable 'interface' (which is a reserved word) you will need to escape it, like this:
var v = from #interface in this.Elements("Interface")
select #interface.Element("InterfaceName").Value;
Probably better to just rename it though....

How to get the names of the namespaces loaded at the beginning

How to get the names of the namespaces loaded at the beginning of a C# file? For example, get the six namespace names below.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Text;
using System.Reflection;
namespace MyNM
{
class MyClass{}
}
This returns all the assemblies references by the executed assembly.
Still, this will NOT return only the namespaces used within a specific file - which is impossible at runtime.
var asms = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
foreach (var referencedAssembly in asms)
{
Console.WriteLine(referencedAssembly.Name);
}
Although, you can, technically, if you know the name of the file which contains your current code, simply read the file at runtime and extract the "using's".
EDIT
The way to do this would be:
public static IEnumerable<string> GetUsings()
{
// Gets the file name of the caller
var fileName = new StackTrace(true).GetFrame(1).GetFileName();
// Get the "using" lines and extract and full namespace
return File.ReadAllLines(fileName)
.Select(line => Regex.Match(line, "^\\s*using ([^;]*)"))
.Where(match => match.Success)
.Select(match => match.Groups[1].Value);
}
How to get the names of the namespaces loaded at the beginning of a C# file? For example, get the six namespace names below.
You can't, other than parsing the file yourself (or using something like the Roslyn CTP to parse a C# file).
Namespaces aren't "loaded" - they are only used by the compile, at compile time, to resolve the appropriate type names.
You can use Assembly.GetReferencedAssemblies to get the assemblies referenced by your assembly (ie: project), but this is an assembly wide set of references, and distinctly different than the namespace using directives included in a specific file.
You have to parse the file to derive the Syntax elements. As mentioned above, you can use System.Reflections for external references or you can use the new Roslyn compiler service as below
string codeSnippet = #"using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Text;
using System.Reflection;
namespace MyNM
{
class MyClass{}
}";
//APPROACH:
//Get using statements in the code snippet from the syntax tree
//find qualified name(eg:System.Text..) in the using directive
SyntaxTree tree = SyntaxTree.ParseCompilationUnit(codeSnippet);
SyntaxNode root = tree.GetRoot();
IEnumerable<UsingDirectiveSyntax> usingDirectives = root.DescendantNodes().OfType<UsingDirectiveSyntax>();
foreach(UsingDirectiveSyntax usingDirective in usingDirectives){
NameSyntax ns = usingDirective.Name;
Console.WriteLine(ns.GetText());
}
NOTE: The code uses older version of Roslyn API. It may break in future as Roslyn is still a CTP.

Categories

Resources