Hello and sorry if question is strange and sorry for bad english.
My code:
xws.OmitXmlDeclaration = true;
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
string lb = "\r\n";
XElement I11 = new XElement("I11", lb,
new XElement("I11_TIPAS", "2"), lb,
new XElement("I11_PAV", "pav"), lb,
new XElement("I11_KODAS_IS", "985"), lb,
from iseip in eip
select new XElement("I12", lb,
new XElement("DI12_BAR_KODAS", iseip.DI12_BAR_KODAS), lb,
new XElement("I12_KODAS_SS", iseip.I12_KODAS_SS), lb,
new XElement("I12_KIEKIS", iseip.I12_KIEKIS), lb,
new XElement("I12_FRAKCIJA", iseip.I12_FRAKCIJA), lb), lb
);
I11.Save(xw);
}
System.IO.File.WriteAllText("bbb.eip", sb.ToString());
Output:
Need get like this:
Problem every I12 node must be in new line. Where is problem?
Try following :
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
List<EIP> eip = new List<EIP>();
using (XmlWriter xw = XmlWriter.Create("bbb.eip", xws))
{
XElement I11 = new XElement("I11", new object[] {
new XElement("I11_TIPAS", "2"),
new XElement("I11_PAV", "pav"),
new XElement("I11_KODAS_IS", "985")
});
foreach(var iseip in eip)
{
XElement I12 = new XElement("I12", new object[] {
new XElement("DI12_BAR_KODAS", iseip.DI12_BAR_KODAS),
new XElement("I12_KODAS_SS", iseip.I12_KODAS_SS),
new XElement("I12_KIEKIS", iseip.I12_KIEKIS),
new XElement("I12_FRAKCIJA", iseip.I12_FRAKCIJA)
});
I11.Add(I12);
}
I11.Save(xw);
}
}
public class EIP
{
public string DI12_BAR_KODAS { get;set;}
public string I12_KODAS_SS { get;set;}
public string I12_KIEKIS { get;set;}
public string I12_FRAKCIJA { get;set;}
}
Try the following.
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(sb.ToString());
xmlDocument.Save(#"D:\\Code2Try\bbb.eip");
XMLDocument saves in proper format.
Related
I wrote a c# class that generate a html file and return this a string.
But I need to add a preview this document HTML (it can be in the browser), and print out option this document.
My code:
public class Class1
{
public string HTMGenerator()
{
string html = "<p>test</p>";
var xDocument = new XDocument(
new XDocumentType("html", null, null, null),
new XElement("html",
new XElement("head"),
new XElement("body"
XElement.Parse(html)),
)
);
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
IndentChars = "\t"
};
using (var sw = new StringWriter())
{
using (var writer = XmlWriter.Create(sw, settings))
{
xDocument.WriteTo(writer);
}
return sw.ToString();
}
}
}
Try this:
string filename = "Your FileName.html";
File.WriteAllText(filename, HTMGenerator());
Process.Start(filename);
Here's how I would write your code:
void Main()
{
var filename ="Your File.html";
var instance = new Class1();
var document = instance.HTMGenerator();
document.Save(filename);
Process.Start(filename);
}
public class Class1
{
public XDocument HTMGenerator()
{
string html = "<p>test</p>";
var xDocument =
new XDocument(
new XDocumentType("html", null, null, null),
new XElement(
"html",
new XElement("head"),
new XElement(
"body",
XElement.Parse(html))));
return xDocument;
}
}
I have this methods in my License Class as shown below.
public void CreateTestLincense(LicenseModel.CustomerLicense objData)
{
string data = CreateXML(objData);
File.WriteAllText(licensePath, data);
}
private string CreateXML(Object YourClassObject)
{
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, YourClassObject);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
return xmlDoc.InnerXml;
}
}
But I'm trying to save the xml after passing its properties.
CustomerLicense custLic = new CustomerLicense();
custLic.CustomerId = 1;
custLic.Names = "David Okwudili";
custLic.Email = "michealdavid910#yahoo.com";
custLic.Phone = "09089786756";
custLic.ExpiringDate = DateTime.Now;
custLic.Serial = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
//Create XML Documant
MAH.Tools.Licensing.License lic = new MAH.Tools.Licensing.License(true);
lic.CreateTestLincense(custLic);
But it has been throwing an exception 'There was an error reflecting type' from XmlSerializer xmlSerializer = new XmlSerializer(YourClassObject.GetType());.
Please i need help, Thanks.
I am doing some XmlOverrides and setting properties to nullable (F1 in this case). I would want to delete nil="true" and the namespace around this attribute, but I can't remove it with any method I've tried.
Nested n = new Nested();
n.Nest = "2";
n.F1 = null;
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes att = new XmlAttributes();
XmlElementAttribute el = new XmlElementAttribute("F1");
el.IsNullable = true;
att.XmlElements.Add(el);
overrides.Add(typeof(Nested), "F1", att);
XmlSerializer xs = new XmlSerializer(typeof(Nested), overrides);
var faultDocument = new XmlDocument();
var nav = faultDocument.CreateNavigator();
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (var writer = nav.AppendChild())
{
xs.Serialize(writer, n, ns);
}
XML I get is like this:
<Nested>
<F1 p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance"/>
<Nest>2</Nest>
</Nested>
But I would want that F1 element be empty, without nil and xmlns
<Nested>
<F1/>
<Nest>2</Nest>
</Nested>
Try to add in Nested class [XmlElement(ElementName = "F1", IsNullable = true)] in property F1.
I managed to solve it, not sure if it's the best way to do it:
private static void RemoveNils(XElement elem)
{
string nilNamespace = "{http://www.w3.org/2001/XMLSchema-instance}nil";
//first condition should be enough, the rest are just fail-safes
if (elem.Attributes().Any(name => name.Name == nilNamespace) && elem.Elements().Count() == 0 && elem.IsEmpty)
{
elem.Attributes().Remove();
return;
}
foreach (XElement el in elem.Elements())
RemoveNils(el);
}
Try this
Nested n = new Nested();
n.Nest = "2";
n.F1 = null;
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes att = new XmlAttributes();
XmlElementAttribute el = new XmlElementAttribute("F1");
el.IsNullable = true;
att.XmlElements.Add(el);
overrides.Add(typeof(Nested), "F1", att);
XmlSerializer xs = new XmlSerializer(typeof(Nested));
var faultDocument = new XmlDocument();
var nav = faultDocument.CreateNavigator();
StringWriter strWriter = new StringWriter();
XmlTextWriter TextWriter = new XmlTextWriter(strWriter);
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(TextWriter, n, ns);
ReqXml = strWriter.ToString();
TextWriter.Close();
return ReqXml;
When I run <!-- This list contains names/words with specific casing - and specific to english only --> will be removed in new destination.
Is there any way to prevent it from happening. I event tried with XDocument.Root same thing happened.
Ps: I know method are not inside class :).
<!-- This list contains names/words with specific casing - and specific to english only -->
<ignore_list>
<name>A.M.</name>
<name>Aaron</name>
<name>Abbie</name>
<name>Abi</name>
<name>Abigail</name>
<name>Abolfazl</name>
<name>Adam</name>
</ignore_list>
private static void EnGBNamesEtc()
{
var listNames = new List<string>(){"some", "names");
var xele = XElement.Load(#"C:\Users\ivandro\Source\subtitleedit\Dictionaries\en_GB_names_etc.xml");
var names = listNames.Except(xele.Elements("name").Select(n => n.Value)).ToList();
foreach (var newName in names)
{
xele.Add(new XElement("name", newName));
}
SaveToNewXml(xele, #"D:\Backup\en_GB_names_etc1.xml");
}
private static void SaveToNewXml(XElement xelem, string dest)
{
XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
var ordered = xelem.Elements("name").OrderBy(element => element.Value).ToList();
using (XmlWriter xw = XmlWriter.Create(dest, xws))
{
xelem.ReplaceAll(ordered);
xelem.Save(xw);
}
}
That's possibly because you're using XElement which only capable of representing single node (when you have two "root" nodes, <ignore_list> and the comment node). Use XDocument instead of XElement to keep the comment node, for example (I tried to keep minimal changes to your original code) :
private static async void EnGBNamesEtc()
{
var listNames = new List<string>(){"some", "names");
var xdoc = XDocument.Load(#"C:\Users\ivandro\Source\subtitleedit\Dictionaries\en_GB_names_etc.xml");
var names = listNames.Except(xdoc.Root.Elements("name").Select(n => n.Value)).ToList();
foreach (var newName in names)
{
xdoc.Root.Add(new XElement("name", newName));
}
SaveToNewXml(xdoc, #"D:\Backup\en_GB_names_etc1.xml");
}
private static void SaveToNewXml(XDocument xdoc, string dest)
{
XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
var ordered = xdoc.Root.Elements("name").OrderBy(element => element.Value).ToList();
using (XmlWriter xw = XmlWriter.Create(dest, xws))
{
xdoc.Root.ReplaceAll(ordered);
xdoc.Save(xw);
}
}
I'm trying to extract some keywords from a text. It works quite fine but I need to remove plurals.
As I'm already using Lucene for searching purpose, I'm trying to use it to extract keyword from indexed terms.
1st, I index the document in a RAMDirectory index,
RAMDirectory idx = new RAMDirectory();
using (IndexWriter writer =
new IndexWriter(
idx,
new CustomStandardAnalyzer(StopWords.Get(this.Language),
Lucene.Net.Util.Version.LUCENE_30, this.Language),
IndexWriter.MaxFieldLength.LIMITED))
{
writer.AddDocument(createDocument(this._text));
writer.Optimize();
}
Then, I extract the keywords:
var list = new List<KeyValuePair<int, string>>();
using (var reader = IndexReader.Open(directory, true))
{
var tv = reader.GetTermFreqVector(0, "text");
if (tv != null)
{
string[] terms = tv.GetTerms();
int[] freq = tv.GetTermFrequencies();
for (int i = 0; i < terms.Length; i++)
list.Add(new KeyValuePair<int, string>(freq[i], terms[i]));
}
}
in the list of terms I can have terms like "president" and "presidents"
How could I remove it?
My CustomStandardAnalyzer use this:
public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
{
//create the tokenizer
TokenStream result = new StandardTokenizer(this.version, reader);
//add in filters
result = new Lucene.Net.Analysis.Snowball.SnowballFilter(result, this.getStemmer());
result = new LowerCaseFilter(result);
result = new ASCIIFoldingFilter(result);
result = new StopFilter(true, result, this.stopWords ?? StopWords.English);
return result;
}
So I already use the SnowballFilter (with the correct language specific stemmer).
How could I remove plurals?
My output from the following program is:
text:and
text:presid
text:some
text:text
text:with
class Program
{
private class CustomStandardAnalyzer : Analyzer
{
public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
{
//create the tokenizer
TokenStream result = new StandardTokenizer(Lucene.Net.Util.Version.LUCENE_30, reader);
//add in filters
result = new Lucene.Net.Analysis.Snowball.SnowballFilter(result, new EnglishStemmer());
result = new LowerCaseFilter(result);
result = new ASCIIFoldingFilter(result);
result = new StopFilter(true, result, new HashSet<string>());
return result;
}
}
private static Document createDocument(string text)
{
Document d = new Document();
Field f = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
f.SetValue(text);
d.Add(f);
return d;
}
static void Main(string[] args)
{
RAMDirectory idx = new RAMDirectory();
using (IndexWriter writer =
new IndexWriter(
idx,
new CustomStandardAnalyzer(),
IndexWriter.MaxFieldLength.LIMITED))
{
writer.AddDocument(createDocument("some text with president and presidents"));
writer.Commit();
}
using (var reader = IndexReader.Open(idx, true))
{
var terms = reader.Terms(new Term("text", ""));
if (terms.Term != null)
do
Console.WriteLine(terms.Term);
while (terms.Next());
}
Console.ReadLine();
}
}